How do I break out of nested loops in Java?
Asked Answered
O

37

2082

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.

I don't want to return the loops. When breaking I'm finished with the execution of the loop block.

Orlon answered 20/5, 2009 at 9:7 Comment(0)
A
2753

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
Anemo answered 20/5, 2009 at 9:11 Comment(3)
This does jump to directly after the loop. Try it! Yes, the label comes before the loop, but that's because it's labeling the loop, rather than the place you want to exit to. (You can continue with a label too.)Anemo
Breaking it up into different methods is only a win if the state is small, or is kept in a form that can be passed by reference. If the state the loops is referring to/manipulating is larger, then an elegant way of breaking out of/continuing the loops becomes a necessity.Payola
Until this answer hit me, never knew Java had concept of labelled loops ¯_(ツ)_/¯Ibiza
B
439

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);
            }
        }
    }
}
Bigwig answered 14/11, 2011 at 18:26 Comment(1)
Sometimes you use several local variables that's outside of the inner loop, passing them all in can feel clunky.Hannigan
S
241

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;
            }
        }
    }
}
Streamliner answered 20/5, 2009 at 9:12 Comment(2)
You don't need to create a new block to use a label.Anemo
No, but it makes the intent a lot clearer. See the first comment on the accepted answer.Circumlocution
D
157

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;
        }
    }
}

By having flag variable ,We can easily control execution of any number of loops ,Just we need to keep this flag value check at loop condition statement as done in main loop->i < 5 && !finished.

Dispread answered 7/12, 2011 at 17:52 Comment(1)
So you're allowing extra loops just so you wouldn't have to label "for"?Radiolucent
A
127

You can use labels:

label1: 
for (int i = 0;;) {
    for (int g = 0;;) {
      break label1;
    }
}
Anson answered 20/5, 2009 at 9:11 Comment(0)
P
46

Use a function:

public void doSomething(List<Type> types, List<Type> types2){
  for(Type t1 : types){
    for (Type t : types2) {
      if (some condition) {
         // Do something and return...
         return;
      }
    }
  }
}
Psychoactive answered 20/5, 2009 at 11:43 Comment(0)
L
24

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;
         }
    }
}
Lunna answered 20/5, 2009 at 9:11 Comment(0)
M
22

Using 'break' keyword alone is not the appropriate way when you need to exit from more than one loops. You can exit from immediate loop No matter with how many loops your statement is surrounded with. You can use 'break' with a label! Here I've used the label "abc" You can write your code as following, within any function in Java

This code shows how to exit from the most outer loop

 abc: 
    for (int i = 0; i < 10; i++) { 
        for (int j = 0; j < 10; j++) { 
           for (int k = 0; k < 10; k++) { 
              if (k == 1){
                 break abc;
              } 
        } 
    } 
}

Also you can use break statement to exit from any loop in a nested loop.

    for (int i = 0; i < 10; i++) { 
       abc:for (int j = 0; j < 10; j++) { 
           for (int k = 0; k < 10; k++) { 
              if (k == 1){
                 break abc;
              } 
        } 
    } 
}

The following code shows an example of exiting from the innermost loop. In other works,after executing the following code, you are at the outside of the loop of 'k' variables and still inside the loop of 'j' and 'i' variables.

    for (int i = 0; i < 10; i++) { 
        for (int j = 0; j < 10; j++) { 
           for (int k = 0; k < 10; k++) { 
              if (k == 1){
                 break;
              } 
        } 
    } 
}
Micronesian answered 17/10, 2020 at 9:2 Comment(0)
C
17

If you don't like breaks and gotos, 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;
        }
    }
}
Camilia answered 21/12, 2013 at 22:56 Comment(2)
Not suitable to foreach loops.Neukam
@JohnMcClane And you're spamming this on many answers on a 9+ year old question because...?Polyzoic
U
13

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;
        }
    }
}
Unionism answered 5/2, 2012 at 6:4 Comment(4)
I don't find it cool to iterate all the items after the condition is broken. Thus I would add a break in the else case.Orlon
@Orlon I'm not sure how you're reaching this conclusion. Once the condition is true, both loops are exited.Unionism
OK, I didn't get the part with the manipulation of the 's' var. But I find that kind of bad style since s is representing the size. Then I prefer the answer from ddyer with explicit vars: https://mcmap.net/q/44997/-how-do-i-break-out-of-nested-loops-in-javaOrlon
@Orlon You can change s to a value which is lower than i or change i to a value greater or equal than s, both should do the trick. You're right about changing s, because it can be used elsewhere later, but changing i won't harm, just will make sure the first for won't continue looping.Septarium
C
11

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; }
}
Cardiograph answered 4/8, 2014 at 17:29 Comment(0)
B
10

Java 8 Stream solution:

List<Type> types1 = ...
List<Type> types2 = ...

types1.stream()
      .flatMap(type1 -> types2.stream().map(type2 -> new Type[]{type1, type2}))
      .filter(types -> /**some condition**/)
      .findFirst()
      .ifPresent(types -> /**do something**/);
Boarhound answered 16/7, 2017 at 10:24 Comment(1)
@Tvde1 and still useful for other users, so new methods and solutions are always welcomeMeteoric
S
10

Labeled break concept is used to break out nested loops in java, by using labeled break you can break nesting of loops at any position. Example 1:

loop1:
 for(int i= 0; i<6; i++){
    for(int j=0; j<5; j++){
          if(i==3)
            break loop1;
        }
    }

suppose there are 3 loops and you want to terminate the loop3: Example 2:

loop3: 
for(int i= 0; i<6; i++){
loop2:
  for(int k= 0; k<6; k++){
loop1:
    for(int j=0; j<5; j++){
          if(i==3)
            break loop3;
        }
    }
}
Surrey answered 4/4, 2019 at 10:15 Comment(0)
S
9

Usually in such cases, it is coming in scope of more meaningful logic, let's say some searching or manipulating over some of the iterated 'for'-objects in question, so I usually use the functional approach:

public Object searching(Object[] types) { // Or manipulating
    List<Object> typesReferences = new ArrayList<Object>();
    List<Object> typesReferences2 = new ArrayList<Object>();

    for (Object type : typesReferences) {
        Object o = getByCriterion(typesReferences2, type);
        if(o != null) return o;
    }
    return null;
}

private Object getByCriterion(List<Object> typesReferences2, Object criterion) {
    for (Object typeReference : typesReferences2) {
        if(typeReference.equals(criterion)) {
             // here comes other complex or specific logic || typeReference.equals(new Object())
             return typeReference;
        }
    }
    return null;
}

Major cons:

  • roughly twice more lines
  • more consumption of computing cycles, meaning it is slower from algorithmic point-of-view
  • more typing work

The pros:

  • the higher ratio to separation of concerns because of functional granularity
  • the higher ratio of re-usability and control of searching/manipulating logic without
  • the methods are not long, thus they are more compact and easier to comprehend
  • higher ratio of readability

So it is just handling the case via a different approach.

Basically a question to the author of this question: what do you consider of this approach?

Snakeroot answered 28/1, 2016 at 18:53 Comment(0)
F
9

Demo

public static void main(String[] args) {
    outer:
    while (true) {
        while (true) {
            break outer;
        }
    }
}
Footpoundal answered 26/8, 2019 at 12:11 Comment(0)
B
8

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");
    }
}
Backslide answered 21/5, 2014 at 14:33 Comment(3)
How would I use this with for-each loops? ;)Kreindler
This doesn't work if you have a more sophisticated loop condition, like list.size()>5. Also it is really just a hack. It's hard to read and bad practice!Balustrade
It is error-prone. Imagine you changed the inner loop to (int k = 0; k < 10; k++) and you didn't fix all of the k = 9 to k = 10. You might get into an infinite loop.Sextans
F
6

Use Labels.

INNER:for(int j = 0; j < numbers.length; j++) {
    System.out.println("Even number: " + i + ", break  from INNER label");
    break INNER;
}

Refer to this article

Fluorspar answered 1/6, 2014 at 12:41 Comment(1)
link doesn't workAnhydrite
C
6

It's fairly easy to use label, You can break the outer loop from inner loop using the label, Consider the example below,

public class Breaking{
    public static void main(String[] args) {
        outerscope:
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (condition) {
                    break outerscope;
                }
            }
        }
    }
}

Another approach is to use the breaking variable/flag to keep track of required break. consider the following example.

public class Breaking{ 
    public static void main(String[] args) {
        boolean isBreaking = false;
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (condition) {
                    isBreaking = true;
                    break;
                }
            }
            if(isBreaking){
                break;
            }
        }
    }
}

However, I prefer using the first approach.

Clariceclarie answered 20/9, 2019 at 11:40 Comment(0)
P
5
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;
    }
}
Preussen answered 11/9, 2013 at 22:14 Comment(0)
B
5

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 BreakLoopException should be internal, private and accelerated with no-stack-trace:

private static class BreakLoopException extends Exception {
    @Override
    public StackTraceElement[] getStackTrace() {
        return new StackTraceElement[0];
    }
}
Bumptious answered 10/10, 2014 at 13:57 Comment(3)
It has been mentioned actually, in an answer getting -23 votes... https://mcmap.net/q/44997/-how-do-i-break-out-of-nested-loops-in-java . It will do the work, but it is a very bad programming practice...Doby
indeed. however I saw such legacy code - 4-levels nested loops with several breaking conditions. and it was more readable with exceptions rather than with inlined code. -23 votes is mostly emotional rating, but yes - this approach should be used carefully.Bumptious
It would have been even more readable if it had been broken out into a separate function call with a center-return. Often made even better by a little refactor so it makes sense as a stand-alone (often reusable) function.Leonerd
C
5

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 < j) {
    if(wanna exit) {
        i = i + j; // if more nested, also add the 
                   // maximum value for the other loops
    }
}
Chequer answered 25/4, 2015 at 22:1 Comment(0)
F
5

Best and Easy Method..

outerloop:
for(int i=0; i<10; i++){
    // here we can break Outer loop by 
    break outerloop;

    innerloop:
    for(int i=0; i<10; i++){
        // here we can break innerloop by 
        break innerloop;
     }
}
Fiester answered 23/8, 2015 at 21:4 Comment(2)
These examples of breaking are imho not very helpful, because even without the label they would break at the same point. Also it's always nice to have code which you can actually execute, which is not the case with your code, since the innerloop can never be reached..Balustrade
I was going to type the same thing. The labels are somewhat useless in this case.Extra
S
5

If it is inside some function why don't you just return it:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
            return value;
         }
    }
}
Seidler answered 25/8, 2016 at 11:25 Comment(1)
I prefer this pattern. It has often caused me to break out the loops into a separate function. My code has always been better after doing so, so for this reason I really like this answer.Leonerd
R
4

Demo for break, continue, and label:

Java keywords break and continue have a default value. It's the "nearest loop", and today, after a few years of using Java, I just got it!

It's seem used rare, but useful.

import org.junit.Test;

/**
 * Created by cui on 17-5-4.
 */

public class BranchLabel {
    @Test
    public void test() {
        System.out.println("testBreak");
        testBreak();

        System.out.println("testBreakLabel");
        testBreakLabel();

        System.out.println("testContinue");
        testContinue();
        System.out.println("testContinueLabel");
        testContinueLabel();
    }

    /**
     testBreak
     a=0,b=0
     a=0,b=1
     a=1,b=0
     a=1,b=1
     a=2,b=0
     a=2,b=1
     a=3,b=0
     a=3,b=1
     a=4,b=0
     a=4,b=1
     */
    public void testBreak() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                if (b == 2) {
                    break;
                }
                System.out.println("a=" + a + ",b=" + b);
            }
        }
    }

    /**
     testContinue
     a=0,b=0
     a=0,b=1
     a=0,b=3
     a=0,b=4
     a=1,b=0
     a=1,b=1
     a=1,b=3
     a=1,b=4
     a=2,b=0
     a=2,b=1
     a=2,b=3
     a=2,b=4
     a=3,b=0
     a=3,b=1
     a=3,b=3
     a=3,b=4
     a=4,b=0
     a=4,b=1
     a=4,b=3
     a=4,b=4
     */
    public void testContinue() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                if (b == 2) {
                    continue;
                }
                System.out.println("a=" + a + ",b=" + b);
            }
        }
    }

    /**
     testBreakLabel
     a=0,b=0,c=0
     a=0,b=0,c=1
     * */
    public void testBreakLabel() {
        anyName:
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                for (int c = 0; c < 5; c++) {
                    if (c == 2) {
                        break anyName;
                    }
                    System.out.println("a=" + a + ",b=" + b + ",c=" + c);
                }
            }
        }
    }

    /**
     testContinueLabel
     a=0,b=0,c=0
     a=0,b=0,c=1
     a=1,b=0,c=0
     a=1,b=0,c=1
     a=2,b=0,c=0
     a=2,b=0,c=1
     a=3,b=0,c=0
     a=3,b=0,c=1
     a=4,b=0,c=0
     a=4,b=0,c=1
     */
    public void testContinueLabel() {
        anyName:
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                for (int c = 0; c < 5; c++) {
                    if (c == 2) {
                        continue anyName;
                    }
                    System.out.println("a=" + a + ",b=" + b + ",c=" + c);
                }
            }
        }
    }
}
Rotorua answered 4/5, 2017 at 7:41 Comment(0)
A
3

for (int j = 0; j < 5; j++) //inner loop should be replaced with for (int j = 0; j < 5 && !exitloops; j++).

Here, in this case complete nested loops should be exit if condition is True . But if we use exitloops only to the upper loop

 for (int i = 0; i < 5 && !exitloops; i++) //upper loop

Then inner loop will continues, because there is no extra flag that notify this inner loop to exit.

Example : if i = 3 and j=2 then condition is false. But in next iteration of inner loop j=3 then condition (i*j) become 9 which is true but inner loop will be continue till j become 5.

So, it must use exitloops to the inner loops too.

boolean exitloops = false;
for (int i = 0; i < 5 && !exitloops; i++) { //here should exitloops as a Conditional Statement to get out from the loops if exitloops become true. 
    for (int j = 0; j < 5 && !exitloops; j++) { //here should also use exitloops as a Conditional Statement. 
        if (i * j > 6) {
            exitloops = true;
            System.out.println("Inner loop still Continues For i * j is => "+i*j);
            break;
        }
        System.out.println(i*j);
    }
}
Aphaeresis answered 8/4, 2016 at 4:29 Comment(0)
O
2

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;
        }
    }
}
Oldworld answered 13/9, 2014 at 19:0 Comment(0)
T
2

If it's a new implementation, you can try rewriting the logic as if-else_if-else statements.

while(keep_going) {

    if(keep_going && condition_one_holds) {
        // Code
    }
    if(keep_going && condition_two_holds) {
        // Code
    }
    if(keep_going && condition_three_holds) {
        // Code
    }
    if(keep_going && something_goes_really_bad) {
        keep_going=false;
    }
    if(keep_going && condition_four_holds) {
        // Code
    }
    if(keep_going && condition_five_holds) {
        // Code
    }
}

Otherwise you can try setting a flag when that special condition has occured and check for that flag in each of your loop-conditions.

something_bad_has_happened = false;
while(something is true && !something_bad_has_happened){
    // Code, things happen
    while(something else && !something_bad_has_happened){
        // Lots of code, things happens
        if(something happened){
            -> Then control should be returned ->
            something_bad_has_happened=true;
            continue;
        }
    }
    if(something_bad_has_happened) { // The things below will not be executed
        continue;
    }

    // Other things may happen here as well, but they will not be executed
    //  once control is returned from the inner cycle.
}

HERE! So, while a simple break will not work, it can be made to work using continue.

If you are simply porting the logic from one programming language to Java and just want to get the thing working you can try using labels.

Travesty answered 1/4, 2017 at 19:54 Comment(0)
M
2

Java does not have a goto feature like there is in C++. But still, goto is a reserved keyword in Java. They might implement it in the future. For your question, the answer is that there is something called label in Java to which you can apply a continue and break statement. Find the code below:

public static void main(String ...args) {
    outerLoop: for(int i=0;i<10;i++) {
    for(int j=10;j>0;j--) {
        System.out.println(i+" "+j);
        if(i==j) {
            System.out.println("Condition Fulfilled");
            break outerLoop;
        }
    }
    }
    System.out.println("Got out of the outer loop");
}
Mis answered 4/8, 2018 at 11:38 Comment(0)
A
1

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");
}
}
Astronomer answered 17/10, 2012 at 11:50 Comment(0)
L
1
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'.

Lionfish answered 11/7, 2014 at 16:46 Comment(0)
A
1

For some cases, We can use while loop effectively here.

Random rand = new Random();
// Just an example
for (int k = 0; k < 10; ++k) {
    int count = 0;
    while (!(rand.nextInt(200) == 100)) {
       count++;
    }

    results[k] = count;
}
Akeylah answered 24/3, 2017 at 1:43 Comment(0)
D
1

You can do the following:

  1. set a local variable to false

  2. set that variable true in the first loop, when you want to break

  3. then you can check in the outer loop, that whether the condition is set then break from the outer loop as well.

    boolean isBreakNeeded = false;
    for (int i = 0; i < some.length; i++) {
        for (int j = 0; j < some.lengthasWell; j++) {
            //want to set variable if (){
            isBreakNeeded = true;
            break;
        }
    
        if (isBreakNeeded) {
            break; //will make you break from the outer loop as well
        }
    }
    
Depress answered 19/9, 2017 at 5:41 Comment(0)
D
1

Below is an example where "break" statement pushes the cursor out of the for loop whenever the condition is met.

public class Practice3_FindDuplicateNumber {

    public static void main(String[] args) {
        Integer[] inp = { 2, 3, 4, 3, 3 };
        Integer[] aux_arr = new Integer[inp.length];
        boolean isduplicate = false;
        for (int i = 0; i < aux_arr.length; i++) {

            aux_arr[i] = -1;

        }
        outer: for (int i = 0; i < inp.length; i++) {
            if (aux_arr[inp[i]] == -200) {
                System.out.println("Duplicate Found at index: " + i + " Carrying value: " + inp[i]);
                isduplicate = true;
                break outer;
            } else {
                aux_arr[inp[i]] = -200;
            }
        }

        for (Integer integer : aux_arr) {
            System.out.println(integer);
        }

        if (isduplicate == false) {
            System.out.println("No Duplicates!!!!!");
        } else {
            System.out.println("Duplicates!!!!!");
        }
    }

}
Dimer answered 8/5, 2019 at 10:20 Comment(0)
D
0

Even creating a flag for the outer loop and checking that after each execution of the 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;
}
Dereism answered 28/4, 2013 at 5:8 Comment(0)
S
0

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   
     } 
}
Separatist answered 7/5, 2013 at 18:57 Comment(0)
C
0

If someone is looking for the kotlin way of adding labeled loops

loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}

Source

Clactonian answered 31/10, 2022 at 12:0 Comment(1)
as you can see nobody does :)Mannino
Y
-10

I feel using labels makes the code seem very much like a goto statement. This is just a thought.

Instead, throw an exception at the inner for loop and encapsulate the two for loops with a try catch block.

Something like

try {
  // ...
  for(Object outerForLoop : objectsOuter) {
     // ...
     for (Object innerForLoop : objectsInner) {
        // ...
        if (isConditionTrue)
             throw new WrappedException("With some useful message. Probably some logging as well.");
     }
  }
  catch (WrappedException) {
        // Do something awesome or just don't do anything to swallow the exception.
  }

Just a thought. I prefer this code since it gives me better loggability (like that's a word) for me when this is being run in production or something.

Yeh answered 31/3, 2016 at 18:33 Comment(4)
Using Exceptions for control flow is not exactly a best practice. So, no it is no option.Orlon
@Orlon what makes you think so?Balustrade
Lots of reading and the opinion of some widely trusted people like uncle Bob oder Martin Fowler.Orlon
I know this question is for java specifically but some people have made the decision to do this in the language design, this is exactly what python's StopIteration is forBrawny

© 2022 - 2024 — McMap. All rights reserved.