break和continue语句更改循环的执行流。
break语句终止循环并将执行转移到紧随循环的语句。
例子:
int x = 1;
while(x > 0) {
System.out.println(x);
if(x == 4) {
break;
}
x++;
}
/* 输出
1
2
3
4
*/
continue语句使循环跳过其主体的其余部分,然后在重复之前立即重新测试其条件。换句话说,它使循环跳到下一个迭代。
例子:
for(int x=10; x<=40; x=x+10) {
if(x == 30) {
continue;
}
System.out.println(x);
}
/* 输出
10
20
40
*/
如您所见,上面的代码按照continue语句的指示跳过值30。