I am trying to print/get the value of loop variable i and use it in another method outside the for loop. How do I do that?
public void mousePressed() {
for (int i = 0; i < 1000; i++){
boxes[i].openIt();
}
}
解决方案
Variables declared in the for statement are in scope only in the for components and the following code block, see JLS section 14.14.1.1, in particular:
for ( ForInit ; Expression ; ForUpdate ) Statement
If the ForInit code is a local variable declaration, it is executed as
if it were a local variable declaration statement (§14.4) appearing in
a block.
If you want to have it available outside the for, you have to declare it in a scope that is active in the location you want to access it; e.g. just outside the for loop:
int i;
for (i = 0; i < 1000; ++ i)
;
// i is accessible in this scope
System.out.println(i);
Alternatively, if it is more appropriate, you could declare a separate variable and store the value of interest in it:
int k = ...;
for (int i = 0; i < 1000; ++ i)
if (condition) // for example
k = i;
// k is accessible in this scope, i is not
System.out.println(k);
For a brief summary see this page, specifically the Loop Scope example at the end, which has an example that is exactly like your question.