Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java multi-level break

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?

like image 307
themaestro Avatar asked Apr 14 '11 21:04

themaestro


2 Answers

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

like image 134
Guido Anselmi Avatar answered Sep 18 '22 19:09

Guido Anselmi


You can do it in 3 ways:

  • You can have while and for loops inside method, and then just call return
  • You can break for-loop and set some flag which will cause exit in while-loop
  • Use label (example below)

This is example for 3rd way (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 1st and 2nd solution is elegant. Some programmers don't like labels.

like image 34
lukastymo Avatar answered Sep 21 '22 19:09

lukastymo