Java提供了break和continue关键字用来控制循环处理。
break关键字主要用于循环语句(while、do...while、for)和switch语句,用来跳出整个语句块。
循环示例:
public class ForDemo03 { public static void main(String[] args) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { System.out.println("输出结果i和j:"+i+"\t"+j); if(j==3){ break; } } } } }
输出结果:
这个示例中有2个for语句,最里面的for语句执行过程中,如果遇到j==3的时,则跳出循环,所以程序执行得结果为最外层每循环一次,最里面就循环4次,打印0~3这4个数字。
switch示例:
public class SwitchDemo01 { public static void main(String[] args) { char score = ‘B‘; switch (score){ case ‘A‘: System.out.println("优秀!"); break; case ‘B‘: System.out.println("良好!"); break; case ‘C‘: System.out.println("中等!"); break; case ‘D‘: System.out.println("及格!"); break; default: System.out.println("还需努力!"); } } }
程序输出结果:
我们试下,把break去掉的话,程序就继续往下执行,我们看输出结果:
public class SwitchDemo01 { public static void main(String[] args) { char score = ‘B‘; switch (score){ case ‘A‘: System.out.println("优秀!"); //break; case ‘B‘: System.out.println("良好!"); // break; case ‘C‘: System.out.println("中等!"); // break; case ‘D‘: System.out.println("及格!"); // break; default: System.out.println("还需努力!"); } } }
输出结果:
continue用来循环语句中结束当次的循环,跳转到下次的循环中,
如果是for语句,则直接跳转到控制变量的更新语句中
如果是while或do..while语句,则跳转到while的布尔表达式中
示例:
public class ForDemo03 { public static void main(String[] args) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { if(j==3){ continue; } System.out.println("输出结果i和j:"+i+"\t"+j); } } } }
输出结果:
程序遇到j=3的时候,程序就跳出当前循环,后面的语句就不再执行了,所以就没有打印J=3的结果出来。
原文:https://www.cnblogs.com/xmboy/p/13872376.html