Reputation: 7571
If I have an int in my for loop, how can I print it out after my for loop. It gets an error saying i is not a variable?
for (int i = 1; i < ar.length; i++) {
}
System.out.println(i);
Upvotes: 0
Views: 53
Reputation: 206916
You can't make local variables (variables declared inside methods) public
; that's only for member variables (variables at class level, declared outside a method).
You have to understand scope. Variables are only visible within a scope. The scope of a local variable is from the point it is defined until the closing }
of the block it is defined in. For variables declared in a for
, the scope is the body of the for
statement (the { ... }
after the for
).
So, the variable i
is does not exist beyond the body of the for
statement.
You have to declare i
outside the for
:
int i;
for (i = 1; i < ar.length; i++) {
// ...
}
System.out.println(i);
Upvotes: 4
Reputation: 361909
for (int i = 1; i < ar.length; i++) {
}
When you declare the variable inside the loop (without public
, mind you), it is only available inside of the loop. If you want to refer to it outside of the loop, move the declaration out of the loop.
int i;
for (i = 1; i < ar.length; i++) {
}
System.out.println(i);
Note that this will only print one line. It'll print the final value of i
after the loop finishes.
If your intention was to print all the values of i
while the loop iterates, instead you should move the print call inside the loop. In that case you could leave i
as a loop variable.
for (int i = 1; i < ar.length; i++) {
System.out.println(i);
}
Upvotes: 1