Java Layered Break

I have a construct where I have a for loop nested inside a while in Java. Is there a way to call the break statement so that it exits the for loop and while ?

+7
source share
5 answers

You can use a β€œtagged” gap for this.

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

}

Taken from: http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

+13
source

You can do this in three ways:

  • You can use the while and for method inside the loop, and then just call return
  • You can break the for-loop and set some flag that will cause exit during the loop
  • Use shortcut (example below)

This is an example of the third method (with label):

  public void someMethod() { // ... 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; } } } } 

example from this site

In my opinion, the first and second solution is elegant. Some programmers do not like shortcuts.

+3
source

Marked Breaks

For example:

 out: while(someCondition) { for(int i = 0; i < someInteger; i++) { if (someOtherCondition) break out; } } 
+2
source

Make a loop inside a function call and return from a function?

+1
source

You should use a label for the outer loop (in this case)

So something like

  label: While() { for() { break label; } } 
+1
source

All Articles