• Register
0 votes
647 views

Problem :

I face the error, as “Local variable defined in an enclosing scope must be final or effectively final” and I want to know from you how to repair it the ERROR is in the menu Item-loop, where I am trying to set my textArea foreground colour to the one picked from the menuItem.

6 5 3
7,540 points

2 Answers

0 votes

Solution :

What you have here is the non-local variable i.e. you are accessing the local variable in a method of an anonymous class.

Local variables of your method are kept on a stack and lost as soon as your method ends, but even after your method ends, the local inner class object is still very much alive on the heap and it will need to access your variable here, when the action is performed.

I want to suggest two workarounds : Either you make your own class which implementsthe  actionlistenner and takes the constructor argument, and your variable and keeps it as the class attribute. So you should only access your variable within your same object.

Or just qualify the copy of your variable final to access it in your inner scope as this error suggests to make it the constant:

This method would suit your case since you are not trying to modify your value of the variable.

9 7 4
38,600 points
0 votes

Solution:

The error means you cannot use the local variable mi inside an inner class.

To use a variable inside an inner class you must declare it final. As long as mi is the counter of the loop and final variables cannot be assigned, you must create a workaround to get mi value in a final variable that can be accessed inside inner class:

final Integer innerMi = new Integer(mi);

So your code will be like this:

for (int mi=0; mi<colors.length; mi++){

    String pos = Character.toUpperCase(colors[mi].charAt(0)) + colors[mi].substring(1);
    JMenuItem Jmi =new JMenuItem(pos);
    Jmi.setIcon(new IconA(colors[mi]));

    // workaround:
    final Integer innerMi = new Integer(mi);

    Jmi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JMenuItem item = (JMenuItem) e.getSource();
                IconA icon = (IconA) item.getIcon();
                // HERE YOU USE THE FINAL innerMi variable and no errors!!!
                Color kolorIkony = getColour(colors[innerMi]); 
                textArea.setForeground(kolorIkony);
            }
        });

        mnForeground.add(Jmi);
    }
}

Error: Local variable must be final

private TimeSlot getStartingTimeSlotAssigned(Request req){
 
  int assignedHour = req.getAssignedHourValue();
		
  if(assignedHour  < 3) {  
    //would like to manipulate/change assignedHourValue if it's less than 3     
    assignedHour  = assignedHour  + 1;
  }
 
  //Error thrown here: Local variable assignedHourValue defined in an enclosing scope must be final or effectively final
  TimeSlot ts = timeSlotList.stream()
	.filter(timeSlot-> (req.getAssignedDatePlanned().getDayOfYear() == timeSlot.getDay().getDayOfYear()) 
			&& (assignedHour == timeSlot.getStartingHourOfDay()))
	.findAny()
	.orElse(null);
 
  return ts;
}

Workaround: Java Lambda Expression and Variable Scope



private TimeSlot getStartingTimeSlotAssigned(Request req){
 
  int[] assignedHour = {req.getAssignedHourValue()};
		
  if(assignedHour[0]  < 3) {      
    assignedHour[0]  = assignedHour[0]  + 1;
  }
  
  TimeSlot ts = timeSlotList.stream()
	.filter(timeSlot-> (req.getAssignedDatePlanned().getDayOfYear() == timeSlot.getDay().getDayOfYear()) 
			&& (assignedHour[0] == timeSlot.getStartingHourOfDay()))
	.findAny()
	.orElse(null);
 
  return ts;
}

 

10 6 4
31,120 points

Related questions

0 votes
1 answer 778 views
778 views
Problem : Currently I am having issues while figuring out why am I receiving below error "Local variables referenced from an inner class must be final or effectively final". My program is running the concurrent threads to sort the array of #'s and then trying to find the high ... myhigh) myhigh = numbers[myindex]; System.out.println(myhigh); } . . . . } Above block of code is producing the error.
asked Dec 25, 2019 alecxe 7.5k points
0 votes
1 answer 46 views
46 views
Problem: Can any one guide me whether the statement is True or False? A local variable can be accessed from anywhere in the program? True False
asked Feb 24 maddi86 5.4k points
3 votes
1 answer 24 views
24 views
Problem: As a beginner, I have a very basic level question. This might be very nonsense to you guys but I need to know. Why is final the only modifier for local variables in Java? I tried to declare final variables with modifiers like all others but it ... -time error, you cannot use modifiers on local variables inside a method except final. I am looking forward to having your explanation. Thanks.
asked Mar 23 Gavin 15.3k points
0 votes
1 answer 54 views
54 views
The scope of a variable is the segment of the program in which the variable can be accessed. Correct Option is; A) True B) False
asked Jun 11 Hiba Waqar 160 points
0 votes
0 answers 14 views