Break label in switch

后端 未结 3 982
既然无缘
既然无缘 2021-01-19 04:42

Edited: Thank you all for your help. I was able to get it working using the the skills I learned in the previous chapters and your advice. Thank you so much!

3条回答
  •  粉色の甜心
    2021-01-19 04:47

    I believe that what you are describing in your problem is some kind of goto functionality and that is not how labels in Java works.

    Java unfortunately supports labels. This is described in this article from Oracle.

    So, basically you can have loops with labels and you can use keyword continue, break and so on to control the flow of the loop.

    The following sample illustrates how to use the loop with the break keyword. When break is invoked it terminates the labeled statement i.e. the statement following someLabel. It does NOT go back to execute where the label was specified.

    someLabel:
        for (i = 0; i < 100; i++) {
            for (j = 0; j < 100; j++) {
                if (i % 20 == 0) {
                    break someLabel;
                }
            }
        }
    

    The continue keyword handles labels the same way. When you invoke e.g. continue someLabel; the outer loop will be continued.

    As per this SO-question you can also do constructs like this:

    BlockSegment:
    if (conditionIsTrue) {
        doSomeProcessing ();
        if (resultOfProcessingIsFalse()) break BlockSegment;
        otherwiseDoSomeMoreProcessing();
        // These lines get skipped if the break statement
        // above gets executed
    }
    // This is where you resume execution after the break
    anotherStatement();
    

    So, basically what happens if you break to a label in your switch you will break that entire statement (and not jump to the beginning of the statement).

    You can test labels further by running the program below. It breaks the while-loop if you enter "quit", otherwise it simply breaks the switch.

    public static void main(String... args) {
        programLoop:
        {
            while (true) {
                Scanner scanner = new Scanner(System.in);
                final String input = scanner.next();
                switch (input) {
                    case "quit":
                        break programLoop; // breaks the while-loop
                    default:
                        break; // break the switch
                }
                System.out.println("After the switch");
            }
        }
    }
    

    Personally, it would take a very special case in order for me to ever recommend using labels. I find that the code gets easier to follow if you instead rearrange your code so that labels are not needed (by e.g. break out complex code to smaller functions).

提交回复
热议问题