Java语言中的各种循环、选择、中断语句和C/C++一般无二。
| 选择结构 | 循环结构 | 中断(跳转) |
| if | for | return |
| if else | while | break |
| if elseif | do while | continue |
| switch | foreach(遍历数组) |
这里主要讲一下,for嵌套循环中出现中断(跳转)语句的情况。
先看如下一段代码(Test.java):
public class Test{
public static void main(String[] args){
System.out.println("The first loop");
for(int i=0;i<5;i++){
for(int j=1;j<10;j++){
if(j%2==0){
continue;
}
System.out.print(j);
}
System.out.print("\n");
}
System.out.println("The second loop");
for(int i=0;i<5;i++){
for(int j=1;j<10;j++){
if(j%2==0){
break;
}
System.out.print(j);
}
System.out.print("\n");
}
}
}
// 输出
// The first loop
// 13579
// 13579
// 13579
// 13579
// 13579
//The second loop
//1
//1
//1
//1
//1
continue用于结束本次循环,当次是针对continue所在的那个小循环(上端代码,continue结束的是for循环里的那个for循环中j%2=0的那个单次循环,继续进行第二个for循环里面的j++操作,而不是外层for循环的i++)。
break用于结束当前循环,上段代码为例,当j%2=0,break结束的是内层for循环的整个操作,不再进行内层循环j++操作,直接返回外层循环,进行i++,然后再进行重新进行内层for循环。
拓展:
如果想当内层循环j%2=0时,用continue实现结束外层for循环的本次循环,可以加一个标签实现,标签名自定,通常用label来表示。
如下段代码(Test1.java):
public class Test1{
public static void main(String[] args){
System.out.println("The first loop");
label:for(int i=0;i<5;i++){
for(int j=1;j<10;j++){
if(j%2==0){
continue label;
}
System.out.print(j);
}
System.out.print("\n");
}
}
}
// 输出
// The first loop
// 11111
使用标签后,一旦内循环j%2=0,则结束外层for循环的本次循环,不再进行内层for循环的j++,而是直接进行外层for循环的i++。
同样,break有也类似的用法,只不过break会结束外层for循环,整个结束,不再进行外层和内层的循序。
代码及结果如下(Test2.java):
public class Test2{
public static void main(String[] args){
System.out.println("The first loop");
label:for(int i=0;i<5;i++){
for(int j=1;j<10;j++){
if(j%2==0){
break label;
}
System.out.print(j);
}
System.out.print("\n");
}
}
}
// 输出
// The first loop
// 1
也许我们在学习过程中,会遇到更复杂的循环嵌套,超过两层,甚至三四层,对于他们的解决方法基本类似,只要分清本次循环和当前循环的“循环”是指的哪个即可。另外,如果嵌套太多的话,一定要试着去优化代码!
原文:http://www.cnblogs.com/-beyond/p/5876329.html