java中的break与continue用法
2017-11-26 17:52
447 查看
注意:JAVA中的标签必须放在循环之前,且中间不能有其他语句。例如:for或while或do-while;
1.使用break退出一层循环(与C/C++中的break用法一样)
Attention:当break用在一组嵌套循环时,将仅跳出最里面的循环。
2.使用break退出多层循环(与C/C++中的goto用法类似,跳过与标签最近的即最外层循环)
程序的输出:
Pass 0: 0 1 2 3 4 5 6 7 8 9 loops complete.
continue的使用
1.在一层循环中的使用(与C/C++中的用法一样)
输出结果:
0 1
2 3
4 5
6 7
8 9
2.在多层循环中使用(提前结束的是标签最近的最外层循环体的一次循环,提前进入最外层循环的下次循环)
结果:
0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
1.使用break退出一层循环(与C/C++中的break用法一样)
1 public static void main(String args[]) 2 { 3 int i=0; 4 while(i<100) 5 { 6 if(i==10) break; 7 System.out.println("i="+i); 8 i++; 9 } 10 }
Attention:当break用在一组嵌套循环时,将仅跳出最里面的循环。
2.使用break退出多层循环(与C/C++中的goto用法类似,跳过与标签最近的即最外层循环)
1 public static void main(String args[]) 2 { 3 outer: 4 for(int i=0; i<3; i++) 5 { 6 System.out.print("Pass "+i+":"); 7 for(int j=0; j<100; j++) 8 { 9 if(j==10) 10 break outer; 11 System.out.print(j+" "); 12 } 13 System.out.println("This will not print"); 14 } 15 System.out.println("loops complete."); 16 }
程序的输出:
Pass 0: 0 1 2 3 4 5 6 7 8 9 loops complete.
continue的使用
1.在一层循环中的使用(与C/C++中的用法一样)
1 public static void main(String args[]) 2 { 3 for(int i=0; i<10; i++) 4 { 5 System.out.print(i+" "); 6 if(i%2==0) 7 continue; 8 System.out.println(""); 9 } 10 }
输出结果:
0 1
2 3
4 5
6 7
8 9
2.在多层循环中使用(提前结束的是标签最近的最外层循环体的一次循环,提前进入最外层循环的下次循环)
1 public static void main(String args[]) 2 { 3 outer: 4 for(int i=0; i<10; i++) 5 6 for(int k=0;k<10;k++) 7 8 { 9 for(int j=0; j<10; j++) 10 { 11 if(j>i) 12 { 13 System.out.println(); 14 continue outer; 15 } 16 System.out.print(" "+(i*j)); 17 }} 18 19 System.out.println(); 20 }
结果:
0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
相关文章推荐
- java中return与break continue的用法说明
- 再探java基础——break和continue的用法
- Java中return,break和continue的用法及区别
- Java中for循环中执行顺序问题及break, continue用法
- break 和continue的用法 java——CSDN
- java (4) - break和continue用法详解 -万万没想到系列(2)
- Java -break,continue,return 用法
- Java中break和continue的用法
- java中 break,continue和return的用法
- Java基础知识2.2-循环嵌套以及break.continue的用法
- 再探java基础——break和continue的用法
- java基础-break和continue用法
- 关于 Java 的break,continue,return 的用法
- 再探java基础——break和continue的用法
- java continue,break,return 三者的区别和用法
- Java 控制语句 break 和 continue 的用法
- JAVA中的break[标签]continue[标签]用法
- java标号—continue,break用法详解
- Java:break/continue/return的用法
- Java中的break,continue关于标签的用法