Appropriate use of multi-level break in Java

I recently encoded a small java program (as a project for the 8086 assembler program), and I got into an interesting position - I needed to exit the while loop from the internal switch statement, something like this (pseudo code, obviously):

:MyLoop
While(foo)
    switch (bar)
       case '1': print '1'; break
       case '0': print '0'; break
       case ';': end while loop;

This seemed like the perfect place for the goto statement, because one β€œbreak” would only come out of the switch statement (especially considering what I designed for the build), but Java doesn't have gotos!

Instead, I found that Java has something called a layered break, so using "break MyLoop" the program would break out of both the switch case and the while loop.

My question then is the appropriate use of a layered gap? If for some reason I wanted to save a switch statement (instead of, say, a nested else ifs), is there an alternative way to simulate a multi-level break through "break" or "continue" alone?

+3
source share
3 answers

Personally, I would usually see this as a hint for reorganizing the loop into my own method - then you can return from the whole method, and not just exit the loop.

, , . (IMO), boolean, , .

+11

- ?

.

"break" "continue"?

, .

+2

Jon Skeet 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
        }
    }
}
+2
source

Source: https://habr.com/ru/post/1751759/


All Articles