Java中Multi-level Break的正确使用
我最近正在编写一个小型 java 程序(作为 8086 汇编程序的设计),并且我遇到了一个有趣的情况 - 我需要从内部 switch 语句退出 while 循环,类似这样的东西(伪代码,显然):
:MyLoop
While(foo)
switch (bar)
case '1': print '1'; break
case '0': print '0'; break
case ';': end while loop;
这似乎是 goto 语句的完美位置,因为单个“break”只会退出 switch 语句(特别是考虑到我正在为汇编进行设计),但 Java 没有 goto!
相反,我发现 Java 有一种称为多级中断的东西,因此通过使用“break MyLoop”,程序将同时跳出 switch case 和 while 循环。 '
那么我的问题是——这是否适合使用多级中断?如果出于某种原因,我想保留 switch (而不是嵌套的 else ifs)语句,是否有另一种方法可以通过单独的“break”或“continue”来模拟多级中断?
I was recently coding a small java program (as design for an 8086 Assembler program) and I wound up in an interesting position -- I needed to exit out of a while loop from an inner switch-statement, something like this (pseudocode, obviously):
:MyLoop
While(foo)
switch (bar)
case '1': print '1'; break
case '0': print '0'; break
case ';': end while loop;
It seemed like the perfect place for a goto statement because a single "break" would only exit the switch statement,(especially considering that I was designing for assembly) but Java has no gotos!
I found instead that Java has something called a multi-level break, so by using "break MyLoop", the program would break out of both the switch case and the while loop. '
My question then -- is this an appropriate use of a multi-level break? If, for some reason, I wanted to keep the switch (instead of, say, nested else ifs) statement, is there an alternative way to mimic a multi-level break via "break" or "continue" alone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就我个人而言,我通常将其视为将循环重构为自己的方法的提示 - 然后您可以从整个方法返回,而不是仅仅打破循环。
我个人认为在大多数情况下这一点更清楚 - 但除此之外,这正是标记中断的用途。它通常比使用单独的布尔变量指示是否继续循环更干净(IMO)。
Personally I would usually regard this as a hint to refactor the loop into its own method - then you can return from the whole method instead of just breaking out of the loop.
I personally find that clearer in most cases - but otherwise, this is exactly the kind of thing that labeled breaks are there for. It's generally cleaner (IMO) than having a separate
boolean
variable indicating whether or not to continue the loop.是的。
您可以设置一个布尔标志,然后在每个级别中断。
Yes.
You could set a boolean flag and then break at each level.
Jon Skeet 在代码中的回答:
Jon Skeet's answer in code: