Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do exit two nested loops? [duplicate]

I have been using Java for quite some time, yet my education in loops is somewhat lacking. I know how to create every loop that exists in java and break out of the loops as well. However, I've recently thought about this:

Say I have two nested loops. Could I break out of both loops using just one break statement?

Here is what I have so far.

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

Is there a way to achieve this?

like image 648
fireshadow52 Avatar asked Jul 10 '11 00:07

fireshadow52


4 Answers

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;
   }
}
like image 110
sirbrialliance Avatar answered Oct 04 '22 01:10

sirbrialliance


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;
like image 41
Grzegorz Szpetkowski Avatar answered Oct 04 '22 01:10

Grzegorz Szpetkowski


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.

like image 30
Dan Tao Avatar answered Oct 04 '22 02:10

Dan Tao


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;
  }
}
like image 33
Blessed Geek Avatar answered Oct 04 '22 02:10

Blessed Geek