How do I break out of nested loops in Java?

前端 未结 30 3301
梦毁少年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

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

提交回复
热议问题