MrD*_*MrD 8 java for-loop while-loop
我有以下代码:
int x = 100; //Or some other value
while(x > 0) {
for(int i = 5; i > 0; i++) {
x = x-2;
if(x == 0)
break;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这只会打破for循环.我怎样才能打破for和while循环呢?
干杯!
您可以使用带标签的中断,将执行重定向到标签标记的块之后:
OUTER:
while(x > 0) {
for(int i = 5; i > 0; i++) {
x = x-2;
if(x == 0)
break OUTER;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然在这种特定情况下,简单break就可以了,因为如果x == 0while也会退出.