简体   繁体   中英

updating a java variable within a for loop based on iteration

I am using Java Swing and i want to change a variable on each radio button selection. I am new to Java and I am not really sure where I am slipping up here...

String[] test = {"red","blue","green","yellow"};

    for(final int i=0; i < test.length; i++)
    {
        RadioItem = new JRadioButtonMenuItem(test[i]);
        RadioItem.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    settingSelection = test[i];
                    JOptionPane.showMessageDialog(null,test[i]);
                };
            });
        settings.add(RadioItem);
        mnSettings.add(RadioItem);
    }

The error I get is:

The final local variable i cannot be assigned. it must be blank and not using a compound assignment.

Can anyone assist?

It's complaining about line:

for(final int i=0; i < test.length; i++)

Here in for loop, you defined i as final and then you are changing the value of i as well (working of for loop). So change it to:

for(int i=0; i < test.length; i++)

Final field or object assigned once cannot be re-assigned another value again.

从循环中删除最终关键字

for(int i=0; i < test.length; i++)

You can declare a variable within a for loop for(int i = 0; i < 10; i++)

what you have done is declare a final variable within the for loop. This can't be done. A final variable cant be changed, its value is set and nothing can change it

Take out the final and just have your loop like for(int i = 0; i < test.length; i++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM