Results 1 to 6 of 6
Thread: breaking out of while loop
- 05-18-2010, 02:20 PM #1
- 05-18-2010, 02:32 PM #2
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 12
If there is no code after the for loop, breaking out of the for loop would mean you proceed to the next while loop iteration. If there is code after the for loop, I'd suggest moving the for loop into a separate method, that returns a boolean, then you can have a continue statement inside the while loop.
Java Code:void method1() { while(some condition) { if(method2()) continue; rest of code } } boolean method2() { for(int i = 0; i < blabla; i++) { if(some condition) return true; rest of code } return false; }
Ever seen a dog chase its tail? Now that's an infinite loop.
- 05-18-2010, 02:57 PM #3
Member
- Join Date
- Apr 2010
- Posts
- 8
- Rep Power
- 0
Java Code:outer_loop: while (true) { for (int i = 0; i < 5; i++) { if (i == 4) { continue outer_loop; } else { System.out.println(i); } } }
IMHO this is a ugly solution, but it works. So this should be used rarely.
If there is no other code in the while loop a simple break will do the trick.Last edited by xerberuz; 05-18-2010 at 03:01 PM.
- 05-18-2010, 03:04 PM #4
Senior Member
- Join Date
- Feb 2009
- Posts
- 312
- Rep Power
- 13
You could always just use a break...
Java Code:while ((currentInputLine = br.readLine()) != null) { for (i=0; i< 35; i++) { if (i == 13) { break;// at this point i need to breakout of for loop AND move onto the next line in while loop. } } }
- 05-18-2010, 03:11 PM #5
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 12
Goto solutions should be avoided, and to StormyWaters, I think the OP has code after the inner for loop as well, but I did cover that eventuality in my post too.
Ever seen a dog chase its tail? Now that's an infinite loop.
- 05-18-2010, 03:21 PM #6
Senior Member
- Join Date
- Feb 2009
- Posts
- 312
- Rep Power
- 13
Similar Threads
-
breaking up a string, a regex problem!!
By A.n.H in forum Advanced JavaReplies: 0Last Post: 05-17-2010, 03:03 PM -
Breaking up of array
By agarwal_srushti in forum New To JavaReplies: 3Last Post: 09-27-2009, 07:03 PM -
Breaking for-loops with listeners?
By CBarry in forum New To JavaReplies: 3Last Post: 04-22-2009, 03:38 AM -
Breaking down an integer
By Emily in forum New To JavaReplies: 1Last Post: 03-06-2008, 06:39 PM -
Breaking from nested switch
By javaplus in forum New To JavaReplies: 3Last Post: 02-02-2008, 08:28 AM
Bookmarks