博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA中的break[标签]continue[标签]用法
阅读量:7303 次
发布时间:2019-06-30

本文共 1364 字,大约阅读时间需要 4 分钟。

原文:

注意:JAVA中的标签必须放在循环之前,且中间不能有其他语句。例如:tag:for或while或do--while;

 

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

转载地址:http://xpxnm.baihongyu.com/

你可能感兴趣的文章
java中的元注解
查看>>
集群文件系统GlusterFS安装配置
查看>>
VMware vSphere常见问题汇总(十六)
查看>>
开放源代码与.NET应用程序平台的性能测试
查看>>
脚本安装apache+php
查看>>
nagios全新的包安装和配置方式
查看>>
客户端操作zookeeper服务代码示例
查看>>
如何选择网管软件呢?
查看>>
SQLSERVER数据库脱机联机实现与作用
查看>>
CentOS6.x配置tomcat搭建JSP应用服务器
查看>>
windows下不打开浏览器访问网页的方法
查看>>
配置内存中OLTP文件组提高性能
查看>>
使用 Graphviz 画拓扑图
查看>>
在Fedora8上配置Apache Httpd
查看>>
Visual Studio中删除所有空行
查看>>
Step Detector and Step Counter Sensors on Android
查看>>
图解Oracle下建立tnsname
查看>>
【分享】兼容各种Linux平台的关闭所有指定名字的进程的命令
查看>>
btrace定位生产故障
查看>>
基于类和基于函数的python多线程样例
查看>>