How do I break out of nested loops in Java?

前端 未结 30 3314
梦毁少年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: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);
                }
            }
        }
    }
    

提交回复
热议问题