I have been using java for quite some time, yet my education in loops is somewhat lacking. I know how to create every loop that exists in java and break out of the loops as well. However, I've recently thought about this:
Say I have two nested loops. Could I break out of both loops using just one break statement?
Here is what I have so far.
int points = 0;
int goal = 100;
while (goal <= 100) {
for (int i = 0; i < goal; i++) {
if (points > 50) {
break; //for loop ends, while loop does not
}
//I know I could put a 'break' statement here and end the while loop but I want to do it using just one 'break' statement
points += i;
}
}
Is there any way to achieve this?
解决方案
In java you can use a label to specify which loop to break/continue:
mainLoop:
while (goal <= 100) {
for (int i = 0; i < goal; i++) {
if (points > 50) {
break mainLoop;
}
points += i;
}
}