1

I am trying to implement an inner class within a loop, and have come into an interesting situation. The internal class has methods, however, when I try and access the variable, Netbeans gives me a compiler error and tells me to make the int final.

As the int is a looping variable, it can not be final. I have tried creating new variables and equating them to the looping variable, but this still throws the same error.

Here is the basic syntax (in pseudo-code):

for(int i = 0; i < 10; i++)
{
     panels[i].printI(new printI(){System.out.println(i);});
}

Any ideas?

Jake Chasan
  • 6,290
  • 9
  • 44
  • 90

3 Answers3

5

Add a temporary final variable to hold the value:

for(int i = 0; i < 10; i++)
{
     final int tmp = i;
     panels[i].printI(new printI(){System.out.println(tmp);});
}
Didier L
  • 18,905
  • 10
  • 61
  • 103
4

This is the idiom:

for(int i = 0; i < 10; i++)
{
  final int j = i;
  panels[i].printI(new printI(){System.out.println(j);});
}
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94
0

Or use the array variant, which saves you one line of code ;)

for(final int[] i = {0}; i[0] < 10; i[0]++)
{
     panels[i[0]].printI(new printI(){System.out.println(i[0]);});
}
qqilihq
  • 10,794
  • 7
  • 48
  • 89