1、含有continue与break的switch在for循环中的用法
public class SwitchTest { public static void p(Object o) { System.out.println(o); } public static void main(String[] args) { int sum = 0; for (int i = 1; i < 5; i++, p("执行迭代后,i = " + i)) { p("执行循环前,i = " + i + ",sum = " + sum); switch (i) { case 1: sum = sum + 2; case 2: sum = sum + 4; p("continue跳出switch,中断当前循环,sum = " + sum); continue; case 3: sum = sum + 16; p("break跳出switch,sum = " + sum); break; default: sum = sum + 4; p("不匹配任何case后,i = " + i + ",sum = " + sum); } p("继续执行当前循环,i = " + i); } p("for循环执行结束,sum = " + sum); } }
输出:
执行循环前,i = 1,sum = 0
continue跳出switch,中断当前循环,sum = 6
执行迭代后,i = 2
执行循环前,i = 2,sum = 6
continue跳出switch,中断当前循环,sum = 10
执行迭代后,i = 3
执行循环前,i = 3,sum = 10
break跳出switch,sum = 26
继续执行当前循环,i = 3
执行迭代后,i = 4
执行循环前,i = 4,sum = 26
不匹配任何case后,i = 4,sum = 30
继续执行当前循环,i = 4
执行迭代后,i = 5
for循环执行结束,sum = 30
分析:continue跳出switch,中断当前循环,然后执行i++,进入下一次循环;break跳出switch,继续执行当前循环。然后执行i++。进入下一次循环。
2、goto语句
public class GotoTest { public static void p(Object o) { System.out.println(o); } public static void main(String[] args) { int j = 0; outer: for (int i = 0;; i++, p("for外迭代后,i=" + i)) { inner: for (; j < 10; j++, p("for内迭代后,j = " + j)) { p("执行for内当前循环前,i = " + i + ", j = " + j); if (j == 2) { p("continue中断for内当前循环"); continue; } if (j == 3) { j++; p("break中断并跳出for内当前循环,执行j++,j=" + j); break; } if (j == 7) { j++; p("continue outer中断for内当前循环并跳转到outer的位置,重新进入outer所指的循环,执行j++,j=" + j); continue outer; } if (j == 8) { p("break outer中断for内当前循环并跳出outer所指的循环"); break outer; } for (int k = 0; k < 5; k++) { if (k == 3) { p("continue inner中断for内当前循环并跳转到inner位置,重新进入inner所指的循环"); continue inner; } } p("继续执行for内当前循环,i=" + i + ",j=" + j); } p("继续执行for外当前循环,i=" + i); } p("for外与for内循环执行结束"); } }
输出:
执行for内当前循环前,i = 0, j = 0
continue inner中断for内当前循环并跳转到inner位置,重新进入inner所指的循环
for内迭代后,j = 1
执行for内当前循环前,i = 0, j = 1
continue inner中断for内当前循环并跳转到inner位置,重新进入inner所指的循环
for内迭代后,j = 2
执行for内当前循环前,i = 0, j = 2
continue中断for内当前循环
for内迭代后,j = 3
执行for内当前循环前,i = 0, j = 3
break中断并跳出for内当前循环,执行j++,j=4
继续执行for外当前循环,i=0
for外迭代后,i=1
执行for内当前循环前,i = 1, j = 4
continue inner中断for内当前循环并跳转到inner位置,重新进入inner所指的循环
for内迭代后,j = 5
执行for内当前循环前,i = 1, j = 5
continue inner中断for内当前循环并跳转到inner位置,重新进入inner所指的循环
for内迭代后,j = 6
执行for内当前循环前,i = 1, j = 6
continue inner中断for内当前循环并跳转到inner位置,重新进入inner所指的循环
for内迭代后,j = 7
执行for内当前循环前,i = 1, j = 7
continue outer中断for内当前循环并跳转到outer的位置,重新进入outer所指的循环,执行j++,j=8
for外迭代后,i=2
执行for内当前循环前,i = 2, j = 8
break outer中断for内当前循环并跳出outer所指的循环
for外与for内循环执行结束
分析:continue中断当前循环,执行迭代,进入下一次循环;break中断并跳出当前循环;带标签的continue中断当前循环并跳转到标签的位置,执行迭代,重新进入标签后的循环;带标签的break中断当前循环并跳出标签所指的循环。
重点:在java里需要使用标签的唯一理由就是因为有循环嵌套存在,且想从多层嵌套中break或continue。