Thursday 26 May 2016

java - Breaking nested loop and main loop




I have the following code:



int x = 100; //Or some other value

while(x > 0) {

for(int i = 5; i > 0; i++) {

x = x-2;


if(x == 0)
break;

}

}


However, this will only break the for loop. How can I have it so that it breaks both the for and the while loops?




Cheers!


Answer



You can use a labeled break, which redirects the execution to after the block marked by the label:



OUTER:
while(x > 0) {
for(int i = 5; i > 0; i++) {
x = x-2;
if(x == 0)

break OUTER;
}
}


Although in that specific case, a simple break would work because if x == 0 the while will exit too.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...