java break停止外层循环和continue继续外层循环

停止外层循环

public class Test {
    public static void main(String[] args) {
        out:for (int i = 0; i < 3; i++) {
            System.out.println("out:" + i);
            for (int j = 0; j < 3; j++) {
                if(i == 1 && j == 1) {
                    break out;
                }
                System.out.println("  in:" + j);
            }
        }
    }
}

输出如下,可以看到(i == 1 && j == 1)条件满足后,内外层循环都停止了

out:0
  in:0
  in:1
  in:2
out:1
  in:0

继续外层循环

public class Test {
    public static void main(String[] args) {
        out:for (int i = 0; i < 3; i++) {
            System.out.println("out:" + i);
            for (int j = 0; j < 3; j++) {
                if(i == 1 && j == 1) {
                    continue out;
                }
                System.out.println("  in:" + j);
            }
        }
    }
}

结果如下,可以看到(i == 1 && j == 1)条件满足后,该次的内层循环停止了,回到外层循环继续

out:0
  in:0
  in:1
  in:2
out:1
  in:0
out:2
  in:0
  in:1
  in:2

停止多层循环

同理可以跳出或者继续多层的循环,只要在要跳出或继续的循环处设置标识即可

public class Test {
    public static void main(String[] args) {
        out:for (int i = 0; i < 3; i++) {
            System.out.println("out:" + i);
            for (int j = 0; j < 3; j++) {
                System.out.println("  in:" + j);
                for (int k = 0; k < 3; k++) {
                    System.out.println("    inner:" + k);
                    if(i == 1 && j == 1 && k== 1) {
                        break out;
                    }
                }
            }
        }
    }
}

输出结果如下

out:0
  in:0
    inner:0
    inner:1
    inner:2
  in:1
    inner:0
    inner:1
    inner:2
  in:2
    inner:0
    inner:1
    inner:2
out:1
  in:0
    inner:0
    inner:1
    inner:2
  in:1
    inner:0
    inner:1

继续多层循环类似,就不贴代码了

 

你可能感兴趣的:(Java)