8

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?

Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
themaestro
  • 13,750
  • 20
  • 56
  • 75
  • http://stackoverflow.com/questions/2545103/is-there-a-goto-statement-in-java/2545160#2545160 there you go :) – Lasse Espeholt Apr 14 '11 at 21:44
  • possible duplicate of [Breaking out of nested loops in Java](http://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java) – Neil May 18 '12 at 21:17

5 Answers5

15

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

Guido Anselmi
  • 3,872
  • 8
  • 35
  • 58
4

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.

lukastymo
  • 26,145
  • 14
  • 53
  • 66
2

Labelled Breaks

For example:

out:
    while(someCondition) {
        for(int i = 0; i < someInteger; i++) {
            if (someOtherCondition)
                break out;
        }
    }
T.K.
  • 2,229
  • 5
  • 22
  • 26
1

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

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
1

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

So something like

    label:
        While()
        {
          for()
          {
             break label;
          }
        }
steffen
  • 16,138
  • 4
  • 42
  • 81
korymiller
  • 357
  • 4
  • 9
  • 21