Reputation: 21
I'm making a quiz program that asks the user simple math questions, recieves an answer, calculates the user's score, etc...
I'm getting an error because I'm using a variable (in this case, x) inside an actionListener:
for(x = 0;x < total;x++){
System.out.print((x+1)+". ");
questionLabel.setText(number1" + "+ number2);
answerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
int returnedAns = Integer.parseInt(answerTextField.getText());
if(returnedAns == answerToTheQuestion){
score++;
System.out.println("correct");
question[x].result = true;
}else{
System.out.println("wrong");
question[x].result = false;
}
try{
Thread.sleep(500);
}catch(Exception e){}
}
});
}
when i run my code, it highlights int x and says 'local variables referenced from an inner clas must be final or effectively final'.
Please help me out I really don't know what to dowhat to do.
I can't mark it as final as I need to be able to change it for the for loop to work...
Upvotes: 0
Views: 909
Reputation: 69
The best way is to define an extra class for this ActionListener implementation.
public class NumberedActionListener implements ActionListener {
private int number;
public NumberedActionListener(int number) {
this.number = number;
}
@Override
public void actionPerformed(ActionEvent e) {
// ...
}
}
Then you can pass an int value to the constructor.
answerButton.addActionListener(new NumberedActionListener(x));
This also looks much better if you like clean code...
Upvotes: 3
Reputation: 1533
You can assign the value of x
to another variable inside the for
-loop and then make that variable final.
for(x = 0;x < total;x++){
final int index = x;
// use index inside your actionListener
}
Upvotes: 1