for (int x = 1; x <= 3; x++) {
System.out.println("Number: " + x);
}
System.out.println("Done! Counted to: " + x);
This gives an error, suggesting to me that I can't access the variable outside the for
loop.
Is there a way to do so?
Declare it outside of the for
statement, then omit the first part of the for
statement.
int x = 1;
for (; x <= 3; x++) {
System.out.println("Number: " + x);
}
System.out.println("Done! Counted to: " + x);
Hint: You can omit any of the three parts of the for
loop. For example, you might wish to omit the last part if you wish to do some conditional incrementing inside of the compound statement that makes up your for
loop.
int x = 1;
for (; x <= 3;) {
if (x % 2 == 0) {
x += 2;
} else {
x++;
}
}
Becareful with this kind of thing though. It's easy to find yourself in an infinite loop if you aren't careful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With