在Java中,break如何与嵌套循环交互?
我知道 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果没有任何修饰,
break
将直接跳出最内层的循环。因此,在这段代码中:break
仅退出循环B
,因此代码将永远循环。然而,Java 有一项称为“命名中断”的功能,您可以在其中命名循环,然后指定要中断的循环。例如:
此代码不会永远循环,因为
break
显式离开循环A
。幸运的是,同样的逻辑适用于
继续
。默认情况下,Continue
执行包含Continue
语句的最内层循环的下一次迭代,但它也可以通过指定标签来跳转到外层循环迭代。一个循环继续执行。在Java以外的语言中,例如C和C++,这种“标记的break”语句不存在,并且不容易跳出多重嵌套循环。可以使用 goto 语句来完成,尽管这通常不受欢迎。例如,假设您愿意忽略 Dijkstra 的建议并使用
goto
,那么 C 中的嵌套中断可能如下所示:希望这会有所帮助!
Without any adornment,
break
will just break out of the innermost loop. Thus in this code:the
break
only exits loopB
, so the code will loop forever.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:
This code will not loop forever, because the
break
explicitly leaves loopA
.Fortunately, this same logic works for
continue
. By default,continue
executes the next iteration of the innermost loop containing thecontinue
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.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 usegoto
:Hope this helps!
默认情况下,它跳出最内层循环。但是您也可以指定标签并使其跳转外循环 。
By default, it jumps out of the innermost loop. But you can specify labels and make it jump of outer loops too.
还可以通过使用Exceptions来突破,这样就可以处理多种原因
You can also break out by using Exceptions, so you can handle multiple reasons
它打破了 1 个循环。很简单。例如:
跳出内循环但仍在外循环中
it breaks 1 loop . very simple. for ex:
break out of inner loop but still in outer loop