开发者

Appropriate use of Multi-level Break in Java

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?


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.


is this an appropriate use of a multi-level break?

Yes.

is there an alternative way to mimic a multi-level break via "break" or "continue" alone?

You could set a boolean flag and then break at each level.


Jon Skeet's answer in code:

public void doSomething() {
    while(foo) {
        switch (bar) {
            case '1': print '1'; break;
            case '0': print '0'; break;
            case ';': return; //Effectively exits the loop
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜