How do I solve local referenced variables inside a for loop?

java declare variable inside loop performance
access variable outside for loop java
create variable in for loop
for loop local variable
for loop two variable java
for loop multiple variables
c++ variables in for loop
java create object inside loop

I'm writing a Swing application and trying to make a menu where each menu item has its own action:

Here's how I wanted to solve this:

private void createGameLevelMenuItems(JMenu menu){
    for (int i = 0; i<10; i++) {
        JMenuItem item = new JMenuItem(new AbstractAction("Level-" + i) {
            @Override
            public void actionPerformed(ActionEvent e) {
                game.loadGame(i);
                board.refresh();
                pack();
            }
        });
        menu.add(item);
    }
}

However, I cannot use loadGame(i), because it says i would have to be final. I understand the reason for this, but I do not know how to work my way around it.

Quick trick: define a final variable at each iteration of the loop that takes the (non final) value of i and use it:

private void createGameLevelMenuItems(JMenu menu){

  for (int i = 0; i<10; i++) {
    final int j = i;   // <--- this line do the thing
    JMenuItem item = new JMenuItem(new AbstractAction("Level-" + j) {
        @Override
        public void actionPerformed(ActionEvent e) {
            game.loadGame(j);
            board.refresh();
            pack();
        }
    });
    menu.add(item);
  }
}

Declaring variables inside loops, good practice or bad practice , This is excellent practice. By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of​  Unless the compiler somehow optimizes your code, declaring a variable inside a for loop will require the allocation of new variables and the collection of old ones. That being said, the compiler does a really good job at optimizing your code.

To add an example to my comment above. You could just create a class implementing AbstractAction, store the i in instance variable and provide it via constructor:

private void createGameLevelMenuItems(JMenu menu){
    for (int i = 0; i<10; i++) {
        JMenuItem item = new JMenuItem(new LoadAction(i));
        menu.add(item);
    }
}

private class LoadAction extends AbstractAction {
    private int i;

    public LoadAction(int i) {
        super("Level-" + i);
        this.i = i;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        game.loadGame(i);
        board.refresh();
        pack();
    }
};

This assumes the game and board are final variables in the encapsulating class, but since you have just a problem with i, I guess it's the case.

Discussion of Why you should stop declaring variables inside a for , Even if this experiment showed that variables inside loops use more It works the same as javascript, you can set all references to an Reusing variables might seem efficient until you need to fix a bug introduced by another developer. Same thing happen when you use the variable as a local one, after  4 How do I solve local referenced variables inside a for loop? Jan 4 '19 4 Cannot pass Object wich extend of a abstract one into a Method with the abstract Object as Parameter Oct 3 '16

Yes, local variables within a function must be final. When I come to this problem, I just define a dummy Variable inside the for loop:

for (int i=0;i<10;i++) {
    int useI = i;
    JMenuItem item = new JMenuItem(new AbstractAction("Level-" + i) {
        @Override
        public void actionPerformed(ActionEvent e) {
            game.loadGame(useI);
            board.refresh();
            pack();
        }
    });
}

How to redefine a variable in a loop after doing something to it, so , How can I use the value of a local variable in Python? Mostly this means that any variable you can reference in a loop can also be modified (rebound): The way you do this in virtually any language is to define the variable outside the  This restriction is required, because referencing a field of a loop variable cannot guarantee the independence of iterations. The following code attempts to reference a field (b) of the loop variable (p) as if it were a structure. Both lines within the loop are invalid.

C# 4.0 Pocket Reference, In the following example, the local variable seed would ordinarily disappear from C# treats those iteration variables as though they were declared outside the loop. The solution, if we want to write 012, is to assign the iteration variable to a​  Your variable exist only inside that loop starting and ending braces. You can use that variable inside those braces only.But if you want to use that variable outside ‘while loop’. It loses it’s scope, you can’t use that variable because it doesn’t exist there. I suggest you to read about “variable scope “, it is easy :-) just search in google.

In Java, how do I use a variable that has been declared in a while loop, You have declared a variable inside the 'while loop'. hmm, yeah nothing wrong here. Your variable exist only inside that loop starting and ending braces. How do i fix this? In above program int i is a local variable of while loop becouse it is declared within the What is the use of interface reference variable in Java? Creating References in C++. Think of a variable name as a label attached to the variable's location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the

C# 8.0 in a Nutshell: The Definitive Reference, The Definitive Reference Joseph Albahari, Eric Johannsen To solve this, you must assign the loop variable to another variable declared Where (c => c != vowel); } This forces a fresh local variable to be captured on each loop iteration. When you learn a language, one of the key points to pay attention to, is the scope of variables. Some examples: 1. Global scope — the variable is visible throughout a compilation unit.

Comments
  • You could just create a class implementing AbstractAction, store the i in instance variable and provide it via constructor.