Is there an easy way to do it? I want to break out of two loops, but the code is also in another loop.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Is there an easy way to do it? I want to break out of two loops, but the code is also in another loop.
Hi,
have you tried using:
break;
?
break only breaks out of the lowest loop you're in.
ex:
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?
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:
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!"); } }
Using labels allows you to break out of several loops at once.
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
helloworld922 (July 2nd, 2009)