以下是对break和continue的用法总结:
(1) 简单的一个continue会退回最内层循环的开头(顶部),并继续执行。
(2) 带有标签的continue会到达标签的位置,并重新进入紧接在那个标签后面的循环
(3) 简单的一个break会中断当前循环(如果标签内是双重循环,那么离开最内层循环)。
(4) 带有标签的break会中断当前循环,并移离由那个标签指示的循环的末尾(如果标签内是双重循环,那么离开这两重循环)。
在循环中可以使用标签,标签在循环中可以改变循环执行的流程。而这不是我们以前单独使用break或者是continue能够达到的。下面还是看看实例吧。
outer1:for(int i =0;i<4;i++){ System.out.PRintln("begin to itrate. "+i); for(int j =0;j<2;j++){ if(i==2){ continue outer1;// break; } System.out.println("now the value of j is:"+j); } System.out.println("******************");} 执行的结果是: begin to itrate. 0 now the value of j is:0 now the value of j is:1 ****************** begin to itrate. 1 now the value of j is:0 now the value of j is:1 ****************** begin to itrate. 2 begin to itrate. 3 now the value of j is:0 now the value of j is:1 ****************** 注:当i=2的时候,continue outer1 使程序回到了outer1最开始循环的位置,开始下一次循环,这个时候执行的循环是i=3而不是重新从i=0开始。同时当使用continue outer1跳出内层循环的时候,外层循环后面的语句也不会执行。也就是是在begin to itrate. 2后面不会出现一串*号了。 对比:outer1:for(int i =0;i<4;i++){ System.out.println("begin to itrate. "+i); for(int j =0;j<2;j++){ if(i==2){// continue outer1; break; } System.out.println("now the value of j is:"+j); } System.out.println("******************");}注:我们直接使用break的话,只是直接跳出内层循环。结果其实就可以看出区别来: begin to itrate. 0 now the value of j is:0 now the value of j is:1 ****************** begin to itrate. 1 now the value of j is:0 now the value of j is:1 ****************** begin to itrate. 2 ****************** begin to itrate. 3 now the value of j is:0 now the value of j is:1 ****************** -----------------------------------------------------------------分割线 我们再来看看break+标签的效果outer2:for(int i =0;i<4;i++){ System.out.println("begin to itrate. "+i); for(int j =0;j<2;j++){ if(i==2){ break outer2;// break; } System.out.println("now the value of j is:"+j); } System.out.println("******************");}结果: begin to itrate. 0 now the value of j is:0 now the value of j is:1 ****************** begin to itrate. 1 now the value of j is:0 now the value of j is:1 ****************** begin to itrate. 2 注:从结果就可以看出当i=2的时候,break+标签直接把内外层循环一起停掉了。而如果我们单独使用break的话就起不了这种效果,那样只是跳出内层循环而已。 最后说一句,java中的标签只适合与嵌套循环中使用。转载自:
[1]http://lihengzkj.iteye.com/blog/1090034
[2]http://blog.csdn.net/whiteotiger/article/details/6522261
新闻热点
疑难解答