Java multi-level break

themaestro picture themaestro · Apr 14, 2011 · Viewed 11k times · Source

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

Answer

Guido Anselmi picture Guido Anselmi · Apr 14, 2011

You can use a 'labeled' break 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