How do exit two nested loops?
本问题已经有最佳答案,请猛点这里访问。
我使用Java已经有相当一段时间了,但我对循环的教育有些欠缺。我知道如何创建Java中存在的每个循环,并且也可以跳出循环。但是,我最近想到了:
Say I have two nested loops. Could I break out of both loops using just one
break statement?
这是我到目前为止所拥有的。
1 2 3 4 5 6 7 8 9 10 11 12 13 | int points = 0; int goal = 100; while (goal <= 100) { for (int i = 0; i < goal; i++) { if (points > 50) { break; // For loop ends, but the 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; } } |
有没有办法做到这一点?
在爪哇中,可以使用标签指定要中断/继续的循环:
1 2 3 4 5 6 7 8 9 | mainLoop: while (goal <= 100) { for (int i = 0; i < goal; i++) { if (points > 50) { break mainLoop; } points += i; } } |
是的,您可以用标签写break,例如:
1 2 3 4 5 6 7 8 9 10 11 12 | int points = 0; int goal = 100; someLabel: while (goal <= 100) { for (int i = 0; i < goal; i++) { if (points > 50) { break someLabel; } points += i; } } // you are going here after break someLabel; |
给这只猫剥皮有很多方法。这里有一个:
1 2 3 4 5 6 7 8 9 10 11 12 | int points = 0; int goal = 100; boolean finished = false; while (goal <= 100 && !finished) { for (int i = 0; i < goal; i++) { if (points > 50) { finished = true; break; } points += i; } } |
更新:哇,不知道如何打破标签。这似乎是一个更好的解决方案。
小学,亲爱的华生…
1 2 3 4 5 6 7 8 9 10 11 12 | int points = 0; int goal = 100; while (goal <= 100) { for (int i = 0; i < goal; i++) { if (points > 50) { goal++; break; } points += i; } } |
或
1 2 3 4 5 6 7 8 9 10 11 12 | int points = 0; int goalim = goal = 100; while (goal <= goalim) { for (int i = 0; i < goal; i++) { if (points > 50) { goal = goalim + 1; break; } points += i; } } |
你不应该使用客观语言的标签。您需要重写for/while条件。
所以您的代码应该如下所示:
1 2 3 4 5 6 7 8 9 | int points = 0; int goal = 100; while (goal <= 100 && points <= 50) { for (int i = 0; i < goal && points <= 50; i++) { points += i; } } // Now 'points' is 55 |
您可以重置循环控制变量。
1 2 3 4 5 6 7 8 9 10 | int points = 0; int goal = 100; while (goal <= 100) { for (int i = 0; i < goal; i++) { if (points > 50) { i = goal = 101; } points += i; } } |