突破嵌套if

CK9*_*920 1 java if-statement break nested-if

我有一些包含嵌套if语句的代码:

if(numberOfNeighbors == 1){

                //go through comparison again, add Pixel(i,j) to current linked list -> complist[numberOfComponents]
                    //  break out of large check ??

                    if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j-1))){ //compare to top left
                        complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break; 
                    }
                    if(ji.getPixelColor(i, j) == (ji.getPixelColor(i,j-1))){ // compare to top
                        complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
                    }

                    if(ji.getPixelColor(i, j) == (ji.getPixelColor(i+1,j-1))){ // compare to top right
                        complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
                    }
                    if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j))){ // compare to left
                        complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
                    }
} // end of if(numberOfNeighbors == 1)
Run Code Online (Sandbox Code Playgroud)

基本上我想做的事情,无论效率如何低,都是比较一下4次,但如果事实证明它是一个匹配,则突破4个嵌套if语句的集合,以及外部if语句.

这会有用吗?或者它是否会突破嵌套,如果它目前在并继续到下一个直到它通过所有4?

Pru*_*hvi 8

重要说明:break语句用于循环而不是分支

我明白你的问题,但使用break的语句出门像循环for,while,do while.if当满足条件并if执行分支内的语句时,您可以退出语句.如果您不想在第一个if满意时检查其他条件,则必须使用if else分支而不是使用4 if语句.这两个链接可能很有用

请参阅以下示例

if(condition) {
    if(condition) { //if this evaluates to true, logic1 is executed
        logic1;
    }
    else if(condition) { //if the above condition fails, but this condition satisfies then logic 2 is executed
        logic2;
    }
    else { //if the above 2 conditions fail, you can execute logic3
        logic3;
    }
}
Run Code Online (Sandbox Code Playgroud)