Breaking out of nested loops in Java
Breaking out of nested loops in Java
I've got a nested loop construct like this:
for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... break; // Breaks out of the inner loop } } }
Now how can I break out of both loops. I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos.
I don't want to put the inner loop in a different method.
Update: I don't want to rerun the loops, when breaking I'm finished with the execution of the loop block.
Answer by Jon Skeet for Breaking out of nested loops in Java
(EDIT: Like other answerers, I'd definitely prefer to put the inner loop in a different method. 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
Answer by simon622 for Breaking out of nested loops in Java
You can use labels:
label1: for (int i = 0;;) { for (int g = 0;;) { break label1; } }
Answer by Miguel Ping for Breaking out of nested loops in Java
You can use a temporary variable:
boolean outerBreak = false; for (Type type : types) { if(outerBreak) break; for (Type t : types2) { if (some condition) { // Do something and break... outerBreak = true; break; // Breaks out of the inner loop } } }
Depending on your function, you can also exit/return from the inner loop:
for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... return; } } }
Answer by Joey for Breaking out of nested loops in Java
You can use a named block around the loops:
search: { for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... break search; } } } }
Answer by Fortega for Breaking out of nested loops in Java
maybe with a function?
public void doSomething(List types, List types2){ for(Type t1 : types){ for (Type t : types2) { if (some condition) { //do something and return... return; } } } }
Answer by Zo72 for Breaking out of nested loops in Java
Technically the correct answer is to label the outer loop. In practice if you want to exit at any point inside an inner loop then you would be better off externalizing the code into a method (a static method if needs be) and then call it.
That would pay off for readability.
The code would become something like that:
private static String search(...) { for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... return search; } } } return null; }
Matching the example for the accepted answer:
public class Test { public static void main(String[] args) { loop(); System.out.println("Done"); } public static void loop() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i * j > 6) { System.out.println("Breaking"); return; } System.out.println(i + " " + j); } } } }
Answer by Elle Mundy for Breaking out of nested loops in Java
I never use labels. It seems like a bad practice to get into. Here's what I would do:
boolean finished = false; for (int i = 0; i < 5 && !finished; i++) { for (int j = 0; j < 5; j++) { if (i * j > 6) { finished = true; break; } } }
Answer by Swifty McSwifterton for Breaking out of nested loops in Java
I needed to do a similar thing, but I chose not to use the enhanced for loop to do it.
int s = type.size(); for (int i = 0; i < s; i++) { for (int j = 0; j < t.size(); j++) { if (condition) { // do stuff after which you want // to completely break out of both loops s = 0; // enables the _main_ loop to terminate break; } } }
Answer by Mahesh P for Breaking out of nested loops in Java
You just use label for breaking inner loops
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"); } }
Answer by tejas for Breaking out of nested loops in Java
Even creating a flag for outer loop and checking that after each execution of inner loop can be the answer.
Like this :
for (Type type : types) { boolean flag=false; for (Type t : types2) { if (some condition) { // Do something and break... flag=true; break; // Breaks out of the inner loop } } if(flag) break; }
Answer by Edd for Breaking out of nested loops in Java
Check if the inner loop is exited with an if statement, by checking the inner loop's variable. You could also create another variable such as a boolean to check if the inner loop is exited.
In this example it uses the inner loop's variable to check if it has been exited:
int i, j; for(i = 0; i < 7; i++){ for(j = 0; j < 5; j++) { if (some condition) { // Do something and break... break; // Breaks out of the inner loop } } if(j < 5){ // Checks if inner loop wasn't finished break; // Breaks out of the outer loop } }
Answer by Panzercrisis for Breaking out of nested loops in Java
boolean broken = false; // declared outside of the loop for efficiency for (Type type : types) { for (Type t : types2) { if (some condition) { broken = true; break; } } if (broken) { break; } }
Answer by zord for Breaking out of nested loops in Java
If you don't like break
s and goto
s, you can use a "traditional" for loop instead the for-in, with an extra abort condition:
int a, b; bool abort = false; for (a = 0; a < 10 && !abort; a++) { for (b = 0; b < 10 && !abort; b++) { if (condition) { doSomeThing(); abort = true; } } }
Answer by Hitendra Hckr for Breaking out of nested loops in Java
You can break from all loops without using any label: and flags.
It's just tricky solution.
Here condition1 is the condition which is used to break from loop K and J. And condition2 is the condition which is used to break from loop K , J and I.
For example:
public class BreakTesting { public static void main(String[] args) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { for (int k = 0; k < 9; k++) { if (condition1) { System.out.println("Breaking from Loop K and J"); k = 9; j = 9; } if (condition2) { System.out.println("Breaking from Loop K, J and I"); k = 9; j = 9; i = 9; } } } } System.out.println("End of I , J , K"); } }
Answer by Rumesh Eranga for Breaking out of nested loops in Java
Use Labels.
INNER:for(int j = 0; j
Refer this article http://javarevisited.blogspot.com/2012/05/break-continue-and-lablel-in-loop-java.html
Answer by astryk for Breaking out of nested loops in Java
boolean condition = false; for (Type type : types) { for (int i = 0; i < otherTypes.size && !condition; i ++) { condition = true; // if your condition is satisfied } }
Use condition as a flag for when you are done processing. Then the inner loop only continues on while the condition has not been met. Either way the outer loop will keep on chuggin'.
Answer by ddyer for Breaking out of nested loops in Java
I prefer to add an explicit "exit" to the loop tests. It makes it clear to any casual reader that the loop may terminate early.
boolean earlyExit = false; for(int i=0;i<10&&!earlyExit; i++) { for(int j=0;i<10&&!earlyExit; j++) { earlyExit=true; } }
Answer by mtyson for Breaking out of nested loops in Java
Like @1800 INFORMATION suggestion, use the condition that breaks the inner loop as a condition on the outer loop:
boolean hasAccess = false; for (int i = 0; i < x && hasAccess == false; i++){ for (int j = 0; j < y; j++){ if (condition == true){ hasAccess = true; break; } } }
Answer by ursa for Breaking out of nested loops in Java
Another one solution, mentioned without example (it actually works in prod code).
try { for (Type type : types) { for (Type t : types2) { if (some condition #1) { // Do something and break the loop. throw new BreakLoopException(); } } } } catch (BreakLoopException e) { // Do something on look breaking. }
Of course break exception should be internal, private and accelerated with no-stack-trace:
private static class BreakLoopException extends Exception { @Override public StackTraceElement[] getStackTrace() { return new StackTraceElement[0]; } }
Answer by user2875404 for Breaking out of nested loops in Java
Rather unusual approach but in terms of code length (not performance) this is the easiest thing you could do:
for(int i=0; i++; i
0 comments:
Post a Comment