Reputation: 125
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?
Upvotes: 4
Views: 6022
Reputation: 107
If the first part is useless, might as well use a while loop then.
int x = 1;
while (x <= 3)
{
System.out.println("Number: " + x);
x++;
}
System.out.println("Done! Counted to: "+ x);
Upvotes: 1
Reputation: 31587
Put x
outside loop and use other variable for loop.
int x = 0;
for (int i = 1; i <= 3; i++) {
System.out.println("Number: " + i);
x = i;
}
System.out.println("Done! Counted to: " + x);
Number: 1
Number: 2
Number: 3
Done! Counted to: 3
Upvotes: 2
Reputation: 17023
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.
Upvotes: 11
Reputation: 2814
When you declare a variable inside for loop, the scope of that variable is only within a loop.
In order to access that variable outside for loop, declare it outside.
int x =0;
for (x=1; x<=3; x++) {
System.out.println("Number: " +x);
}
System.out.println("Done! Counted to: "+x);
}
}
Upvotes: 1
Reputation: 2698
Yes, very easily. Just do it like this:
int x = 0;
for (x=1; x<=3; x++) {
System.out.println("Number: " +x);
}
System.out.println("Done! Counted to: "+x);
You don't have to declare a new variable in the loop, you can use an existing one if you want to.
Upvotes: 1
Reputation: 13242
int x=1;
for (; x<=3; x++) {
System.out.println("Number: " +x);
}
System.out.println("Done! Counted to: "+x);
Upvotes: 0