在Java中,break如何与嵌套循环交互? [英] In Java, how does break interact with nested loops?
问题描述
我知道 break
语句跳出循环,但是它是跳出嵌套循环还是只跳出它当前的循环?
I know a break
statement jumps out of a loop, but does it jump out of nested loops or just the one its currently in?
推荐答案
没有任何装饰, break
将突破最里面的循环。因此,在此代码中:
Without any adornment, break
will just break out of the innermost loop. Thus in this code:
while (true) { // A
while (true) { // B
break;
}
}
休息
只退出循环 B
,因此代码将永远循环。
the break
only exits loop B
, so the code will loop forever.
但是,Java有一个功能称为命名中断,您可以在其中命名循环,然后指定要突破的循环。例如:
However, Java has a feature called "named breaks" in which you can name your loops and then specify which one to break out of. For example:
A: while (true) {
B: while (true) {
break A;
}
}
此代码不会永远循环,因为 break
显式离开循环 A
。
This code will not loop forever, because the break
explicitly leaves loop A
.
幸运的是,这同样的逻辑适用于继续
。默认情况下, continue
执行包含 continue
语句的最内层循环的下一次迭代,但它也可用于通过指定循环标签继续执行来跳转到外循环迭代。
Fortunately, this same logic works for continue
. By default, continue
executes the next iteration of the innermost loop containing the continue
statement, but it can also be used to jump to outer loop iterations as well by specifying a label of a loop to continue executing.
在Java以外的语言中,例如C和C ++,这个标记为中断 语句不存在,并且打破多重嵌套循环并不容易。它可以使用 goto
语句来完成,尽管这通常是不受欢迎的。例如,假设您愿意忽略Dijkstra的建议并使用 goto
:
In languages other than Java, for example, C and C++, this "labeled break" statement does not exist and it's not easy to break out of a multiply nested loop. It can be done using the goto
statement, though this is usually frowned upon. For example, here's what a nested break might look like in C, assuming you're willing to ignore Dijkstra's advice and use goto
:
while (true) {
while (true) {
goto done;
}
}
done:
// Rest of the code here.
希望这有帮助!
这篇关于在Java中,break如何与嵌套循环交互?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!