0

Why can't I change the x++'s location??

int x = 1; while(x > 0) { System.out.println(x); if(x == 4) { break; x++; } } /* Outputs 1 2 3 4 */ in the lines above, the 'x++;' was located between two last curly braces. I wanted to add 1 right after break is done. So I moved it to the current location, but this doesn't work. If I want to activate the 'break' on 'while', am I unable to place something inside that 'break's curly brace?

2nd Oct 2017, 7:00 AM
Winters
Winters - avatar
2 odpowiedzi
+ 3
You placed the x++ statement within the if block. Now, it will only run when the if statement is true, which is never, because x will not increment in the loop, thus creating an infinite loop. If you remove the if statements curly braces the code will run fine due to there only being the one statement that needs to be run within the if statement. int x = 1; while(x > 0) { System.out.println(x); if(x == 4) break; x++; }
2nd Oct 2017, 7:13 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
thanks, now I see
2nd Oct 2017, 7:24 AM
Winters
Winters - avatar