How do exit two nested loops? [duplicate]

风格不统一 提交于 2019-12-02 17:00:45
sirbrialliance

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

Yes, you can write break with label e.g.:

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;

There are many ways to skin this cat. Here's one:

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

Update: Wow, did not know about breaking with labels. That seems like a better solution.

Elementary, dear Watson ...

int points = 0;
int goal = 100;

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

or

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

You can reset the loop control 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;
   }
}
Kacper Obrzut

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!