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

break, for-loop, java, loops, syntax

Solution

Using a labeled break:

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

Also See

- “loop:” in Java code. What is this, and why does it compile?

- Documentation

Problem

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. } } } } ```

Original source

Related problems