How do I break out of nested loops in Java?

前端 未结 30 2796
梦毁少年i
梦毁少年i 2020-11-21 11:51

I\'ve got a nested loop construct like this:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do somethin         


        
相关标签:
30条回答
  • 2020-11-21 12:15

    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.

    0 讨论(0)
  • 2020-11-21 12:17

    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;
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-21 12:17

    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; }
    }
    
    0 讨论(0)
  • 2020-11-21 12:22

    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
        }
    }
    
    0 讨论(0)
  • 2020-11-21 12:23

    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;
             }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 12:25

    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);
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题