Using label and break in if-else statement

為{幸葍}努か 提交于 2020-06-25 07:08:39

问题


I have this code which generates random number from an array, at a particular condition (when x and y both are equal to zero). I want the control to jump to the label. But the control never jumps to the label in any condition. I wanted to know that whether I am doing it right or not?

int[] arr = {0, 1, 2};    
Random rn = new Random();
label: {
    //some code
    if (x != 0 && y !=0) {
        //some code
    } else {
        break label;
    }
}

回答1:


Try to Avoid using labels. What you could do there, is:

while(true) {
    if(x == 0 && y == 0) {
        break;
    }
    // some stuff with x and y
}



回答2:


Without examining whether you should, yes, you can use labeled statements with if in Java. According to the 1.7 specification

The Identifier is declared to be the label of the immediately contained Statement. [...] identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.

It goes on (emphasis added)

If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason.

So if you break an if block (remember a block is a statement), you can exit the if body. Let's test it:

public static void main(String[] args) {
    if (true) label: {
        if (args != null)
            break label;
        System.out.println("doesn't get here");
    }
    System.out.println("Outside of labeled block");
}

Output:

Outside of labeled block



回答3:


The break statement breaks loops and does not transfer control to the label.

Using a label with break is for when you have inner and outer loops. An unlabeled break breaks the inner most loop (the one you are in) whereas a labeled break allows you to specify an outer loop.

See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Specifically the BreakWithLabelDemo




回答4:


I suggest that you use a recursive function.

public void work(){
    // some code
    if (x != 0 && y != 0) {
        //some code
    } else {
        work();
    }
} 

You cannot use break without loops




回答5:


As far as I know, labels cannot be used arbitrarily around {}, you need to do them to mark a for, while or do-while loop



来源:https://stackoverflow.com/questions/14835815/using-label-and-break-in-if-else-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!