Saturday, June 29, 2019

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





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



Using a labeled break:



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

}





Also See




No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...