Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an integer outside its for loop

Tags:

java

int

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?

like image 709
arkmabat Avatar asked Dec 04 '22 08:12

arkmabat


1 Answers

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.

like image 69
crush Avatar answered Dec 29 '22 05:12

crush