如何退出两个嵌套循环?

时间:2011-07-10 00:06:56

标签: java loops break nested-loops

我已经使用Java很长一段时间了,但我的循环教育有点缺乏。我知道如何创建java中存在的每个循环,并打破循环。但是,我最近想过这个:

  

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

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

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

有没有办法实现这个目标?

6 个答案:

答案 0 :(得分:83)

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

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

答案 1 :(得分:19)

是的,你可以写break with label例如:

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;

答案 2 :(得分:6)

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

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

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

答案 3 :(得分:1)

小学,亲爱的沃森......

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

答案 4 :(得分:0)

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

select 
  name, type 
from 
  mysql.proc 
where 
  db = database() 
order by 
  type, name;

答案 5 :(得分:0)

You shouldn't use labels in objective language. You need to rewrite the for/while condition.

So your code should look like:

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