如何退出两个嵌套循环

我一直在使用Java很长一段时间,但我的循环教育有点缺乏。 我知道如何创buildJava中存在的每个循环,并跳出循环。 不过,我最近想到这个:

说我有两个嵌套循环。 我可以使用一个break语句break两个循环吗?

这是我迄今为止。

 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; } } 

有没有办法做到这一点?

在Java中,您可以使用标签来指定要打断/继续的循环:

 mainLoop: while (goal <= 100) { for (int i = 0; i < goal; i++) { if (points > 50) { break mainLoop; } points += i; } } 

是的,你可以写标签rest,例如:

 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; 

有很多方法来剥皮这只猫。 这里有一个:

 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; } } 

更新 :哇,不知道打破标签。 这似乎是一个更好的解决scheme。

小学,亲爱的华生

 int points = 0; int goal = 100; while (goal <= 100) { for (int i = 0; i < goal; i++) { if (points > 50) { goal++; break; } points += i; } } 

要么

 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; } } 

您可以重置循环控制variables。

 int points = 0; int goal = 100; while (goal <= 100) { for (int i = 0; i < goal; i++) { if (points > 50) { i = goal = 101; } points += i; } } 

你不应该用客观的语言来使用标签。 你需要重写/ while条件。

所以你的代码应该如下所示:

 int points = 0; int goal = 100; while (goal <= 100 && points <= 50) { for (int i = 0; i < goal && points <= 50; i++) { points += i; } } // now points are 55