How to break out of nested loops?
Use:
if (condition) {
i = j = 1000;
break;
}
How do I break out of nested loops in Java?
Like other answerers, I'd definitely prefer to put the loops in a different method, at which point you can just return to stop iterating completely. This answer just shows how the requirements in the question can be met.
You can use break
with a label for the outer loop. For example:
public class Test {
public static void main(String[] args) {
outerloop:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");
}
}
This prints:
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
Breaking
Done
How can I break out of multiple loops?
My first instinct would be to refactor the nested loop into a function and use return
to break out.
Breaking out of nested loops
It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.
In the rejection message, Mr van Rossum mentions using return
, which is really sensible and something I need to remember personally. :)
What's the best way to break from nested loops in JavaScript?
Just like Perl,
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
as defined in EMCA-262 section 12.12. [MDN Docs]
Unlike C, these labels can only be used for continue
and break
, as Javascript does not have goto
.
Python-Break out of nested loops
I found the answer to be, to just include the code that I want to execute afterwards, in the else statment.
As shown here:
for i in range(10):
for j in range(10):
print(i*j)
if testfunction(i,j):
break
else:
executecode(i,j) # only gets executed if testfunction was never true
Breaking out of a nested loop
Well, goto
, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use return
to exit back to the main code.
// goto
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
goto Foo; // yeuck!
}
}
Foo:
Console.WriteLine("Hi");
vs:
// anon-method
Action work = delegate
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits anon-method
}
}
};
work(); // execute anon-method
Console.WriteLine("Hi");
Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:
// local function (declared **inside** another method)
void Work()
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits local function
}
}
};
Work(); // execute local function
Console.WriteLine("Hi");
How to break out of nested loops in Go?
use function
package main
import (
"fmt"
)
func getWord() string {
word := ""
for word != "DC" {
for _, i := range "ABCDE" {
for _, j := range "ABCDE" {
word = string(i) + string(j)
fmt.Println(word)
if word == "DC" {
return word
}
}
}
}
return word
}
func main(){
word := getWord()
}
Edit: thanks to @peterSO who points on some mistakes in the details and provides this playground https://play.golang.org/p/udcJptBW9pQ
Related Topics
Pygame.Event.Get() Not Returning Any Events When Inside a Thread
How to Check If the String Is Empty
Is There a List of Pytz Timezones
How to Convert JSON Data into a Python Object
Check for Presence of a Sliced List in Python
Pandas Dataframe Line Plot Display Date on Xaxis
Differences Between Distribute, Distutils, Setuptools and Distutils2
Python Max Function Using 'Key' and Lambda Expression
Very Large Matrices Using Python and Numpy
How to Draw Vertical Lines on a Given Plot
Calculating a Directory's Size Using Python
How to Start a Python File While Windows Starts
Editing Specific Line in Text File in Python
Pandas Groupby.Apply Method Duplicates First Group
Syntax Behind Sorted(Key=Lambda: ...)
Getting "Permission Denied" When Running Pip as Root on My MAC