1、终止单层和多层循环break的使用:
break:终止单层循环
break结合标签的使用可以终止多层循环
演示案例:
class BreakDemo {
public static void main(String[] args) {
//在 switch 或 loop 外部中断
//break;
//跳出单层循环
for(int x=0; x<10; x++) {
if(x == 3) { break; }
System.out.println("HelloWorld");
}
System.out.println("over");
System.out.println("-------------");
wc:for(int x=0; x<3; x++) {
nc:for(int y=0; y<4; y++) {
if(y == 2) {
//break nc;
break wc;
}
System.out.print("*");
}
System.out.println();
}
}
}
运行结果:
HelloWorld
HelloWorld
HelloWorld
over
-------------
**
break:跳出单层循环
continue:跳出一次循环,进入下一次的执行
class ContinueDemo {
public static void main(String[] args) {
for(int x=0; x<10; x++) {
if(x == 3) { /*break;*/continue; }
System.out.println(x);
}
}
}
输出:0 1 2 4 5 6 7 8 9