How do I break from the main/outer loop in a double/nested loop?

Shepard picture Shepard · Oct 25, 2012 · Viewed 30.8k times · Source

If I have loop in a loop and once an if statement is satisfied I want to break main loop, how am I supposed to do that?

This is my code:

for (int d = 0; d < amountOfNeighbors; d++) {
    for (int c = 0; c < myArray.size(); c++) {
        if (graph.isEdge(listOfNeighbors.get(d), c)) {
            if (keyFromValue(c).equals(goalWord)) { // Once this is true I want to break main loop.
                System.out.println("We got to GOAL! It is "+ keyFromValue(c));
                break; // This breaks the second loop, not the main one.
            }
        }
    }
}

Answer

Jigar Joshi picture Jigar Joshi · Oct 25, 2012

Using a labeled break:

mainloop:
for(){
 for(){
   if (some condition){
     break mainloop;
   }
  }
}

Also See