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. } } } }
There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.
The outer loop must contain an if block after the inner loop. The if block must check the value of the flag variable and contain a break statement. If the flag variable is True, then the if block will be executed and will break out of the inner loop also.
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
Using a labeled break:
mainloop: for(){ for(){ if (some condition){ break mainloop; } } }
Also See
You can add labels to your loop, and use that labelled break
to break out of the appropriate loop: -
outer: for (...) { inner: for(...) { if (someCondition) { break outer; } } }
See these links for more information:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With