break和continue关键字的使用

  使用范围  循环中使用的作用(不同点) 相同点
break switch-case 结束当前循环 关键字后面不能声明执行语句
continue 循环结构中 结束当次循环 关键字后面不能声明执行语句

带标签的break是跳出循环到标签处而继续进行程序后边的语句

带标签的continue是直接进行标签处的下一次循环。


版权声明:本文为CSDN博主「样young」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jisuanjiguoba/article/details/81075819

Java中提供了带标签的break和continue语句用于中断控制流程语句。首先我们先来测试一下不带标签的break和continue语句:

 1 public class Test3 {
 2     public static void main(String[] args) {
 3         for(int i=0;i<5;i++) {
 4             for(int j=0;j<5;j++) {
 5                 if(j==3) {
 6                     break;
 7                 }
 8                 System.out.print(""+i+j+" ");            
 9             }
10             System.out.println();
11         }
12         System.out.println("This is end");
13     }
14 }
15  
16 输出:
17 00 01 02 
18 10 11 12 
19 20 21 22 
20 30 31 32 
21 40 41 42 
22 This is end
23  
24 将break改为continue时输出:
25 00 01 02 04 
26 10 11 12 14 
27 20 21 22 24 
28 30 31 32 34 
29 40 41 42 44 
30 This is end
31 ————————————————

可见break不带标签时是跳出内部循环,从而继续进行外部循环;而continue不带标签时直接进行内部循环的下一次迭代,并不跳出内部循环。

下面进行带标签的break和continue测试:

 1 public class Test3 {
 2     public static void main(String[] args) {
 3         for(int i=0;i<5;i++) {
 4             Label_out:
 5             for(int j=0;j<5;j++) {
 6                 if(j==3) {
 7                     break Label_out;
 8                 }
 9                 System.out.print(""+i+j+" ");            
10             }
11             System.out.println();
12         }
13         System.out.println("This is end");
14     }
15 }
16  
17 输出:
18 00 01 02 
19 10 11 12 
20 20 21 22 
21 30 31 32 
22 40 41 42 
23 This is end
24  
25 把break Label_out改为continue Label_out时输出:
26 00 01 02 04 
27 10 11 12 14 
28 20 21 22 24 
29 30 31 32 34 
30 40 41 42 44 
31 This is end

可见此时的输出结果与不带标签时的结果一致,但是当把Label_out移到外循环前时:

 1 public class Test3 {
 2     public static void main(String[] args) {
 3         Label_out:
 4         for(int i=0;i<5;i++) {
 5             for(int j=0;j<5;j++) {
 6                 if(j==3) {
 7                     break Label_out;
 8                 }
 9                 System.out.print(""+i+j+" ");            
10             }
11             System.out.println();
12         }
13         System.out.println("This is end");
14     }
15 }
16  
17 输出:
18 00 01 02 This is end
19  
20 把break Label_out改为continue Label_out时输出:
21 00 01 02 10 11 12 20 21 22 30 31 32 40 41 42 This is end

可见带标签的break是跳出循环到标签处而继续进行程序后边的语句;带标签的continue是直接进行标签处的下一次循环。


原文地址:https://www.cnblogs.com/rijiyuelei/p/12323213.html