break主要用于循环语句或者switch语句中,用来跳出整个语句块。
break跳出最里层的循环,并继续执行该循环下面的语句。
public class Break {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
// x 等于 30 时跳出循环
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
编译并运行,结果如下
10
20
continue适用于任何循环结构,用于使程序立刻跳转到下一次循环。
在for循环中,continue语句使程序立即跳转到更新语句。
在while或者do…while循环中,程序立即跳转到布尔表达式的判断语句。
public class Continue {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {//x=30时进入下一次循环
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
编译并运行,结果如下
10
20
40
50