Breaking out of multiple loops

• June 30th, 2009, 12:34 PM
helloworld922
Breaking out of multiple loops
Is there an easy way to do it? I want to break out of two loops, but the code is also in another loop.
• June 30th, 2009, 05:32 PM
Dalisra
Re: Breaking out of multiple loops
Hi,
have you tried using:
break;
?
• June 30th, 2009, 06:42 PM
helloworld922
Re: Breaking out of multiple loops
break only breaks out of the lowest loop you're in.
ex:
Code :

```while(cond1) { doit1(); while(cond2) { doit2(); while (cond3) { doit3(); if (cond4) { // break out to cond1 while loop } } doit4(); } doit5(); }```

what would you put in place of the comment to fulfill that task?
• July 1st, 2009, 08:01 AM
Dalisra
Re: Breaking out of multiple loops
I wrote a short code to test my theory and it worked, however I believe you can reuse and optimize the code in a better way to get the same results, this is just an example how to do it:

Code :

```package Random;   public class BreakWhileLoops {   /** * @param args */ public static void main(String[] args) {   int i=0; boolean loopOneBreak = false; while (true){ //while 1 while(true){ //while 2 while(true){ //while 3 i++; if(i>5){ loopOneBreak = true; } if (loopOneBreak){ break; //break while 3 } System.out.println("while 3: " + i); } if (loopOneBreak){ break; // break while 2 } System.out.println("while 2: " + i); } if (loopOneBreak){ break; //break while 1 } System.out.println("while 1: " + i); } System.out.println("Ended while loops succsessfully!");   }   }```
• July 1st, 2009, 02:52 PM
Json
Re: Breaking out of multiple loops
Using labels allows you to break out of several loops at once.

Code :

```class BreakWithLabelDemo { public static void main(String[] args) {   int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12;   int i; int j = 0; boolean foundIt = false;   search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } }   if (foundIt) { System.out.println("Found " + searchfor + " at " + i + ", " + j); } else { System.out.println(searchfor + " not in the array"); } } }```

// Json