java-如何退出两个嵌套循环?

这个问题已经在这里有了答案:

  • 如何突破Java中的嵌套循环? 35个答案

我使用Java已经有一段时间了,但是我对循环的学习还是有些不足。 我知道如何创建存在于Java中的每个循环以及如何打破循环。 但是,最近我想到了:

说我有两个嵌套循环。 我可以只使用一条3005080801336886882语句来打破两个循环吗?

这是我到目前为止所拥有的。

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

有没有办法做到这一点?

fireshadow52 asked 2020-08-10T10:15:00Z
6个解决方案
83 votes

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

mainLoop:
while (goal <= 100) {
   for (int i = 0; i < goal; i++) {
      if (points > 50) {
         break mainLoop;
      }
      points += i;
   }
}
sirbrialliance answered 2020-08-10T10:15:07Z
19 votes

是的,您可以使用标签写中断,例如:

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;
Grzegorz Szpetkowski answered 2020-08-10T10:15:26Z
6 votes

有很多方法可以给这只猫蒙皮。 这是一个:

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

更新:哇,不知道如何破坏标签。 这似乎是一个更好的解决方案。

Dan Tao answered 2020-08-10T10:15:51Z
1 votes

小学,亲爱的沃森...

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;
  }
}
Blessed Geek answered 2020-08-10T10:16:15Z
0 votes

您可以重置循环控制变量。

int points = 0;
int goal = 100;
while (goal <= 100) {
   for (int i = 0; i < goal; i++) {
      if (points > 50) {
         i = goal = 101;
      }
   points += i;
   }
}
Dipto_Das answered 2020-08-10T10:16:35Z
0 votes

您不应该使用客观语言的标签。您需要重写for / 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' is 55
Kacper Obrzut answered 2020-08-10T10:16:59Z
translate from https://stackoverflow.com:/questions/6638321/how-do-exit-two-nested-loops