如何跳过if语句转到下一个if语句

时间:2015-12-11 19:23:20

标签: java

是否可以跳过if语句并在if语句中执行另一个if语句?

if(...){
    A code.
}else if(...){
    B. Call to C.
}else if(...){
    C code.
}else(...){
    D code.
}

E.g。如果我在包含A的if语句中,并且条件发生变化以便执行B,那么如何在B else if语句中调用C WHILST 中的代码。

EDIT =忘了说我的if语句除了一个返回一个名为Dice []的自定义对象数组。我已经实现了以下解决方案,现在收到返回语句错误。

public Die[] ifA(){
A
}

public void ifB(){
ifC(); ifD();
}
public Die[] ifC(){
C
}
public Die[] ifD(){
D
}

public Die[] roll(){

if(...){ return ifA();
}else if(...){ifC();ifD();
}else if(...){return ifC();    
}else(...){return ifD();
}

}

我刚刚在roll()方法结束时收到返回错误。当然我不应该因为我使用了else {}块,因此如果没有执行if / else if语句,则必须运行else,不是吗?

编辑#2 =刚刚找到了没有返回值的方法的解决方法。谢谢你们的意见。使我的代码更整洁,更容易理解!

3 个答案:

答案 0 :(得分:6)

您可以将A CodeB CodeC CodeD Code放入自己的方法中,然后在{{1}中调用C Code if语句。

例如

B

和if-else-block

public void doA() {
    //Do what would happen in A
}
public void doB() {
    //Do what would happen in B
}
public void doC() {
    //Do what would happen in C
}
public void doD() {
    //Do what would happen in D
}

答案 1 :(得分:4)

为c代码创建方法。

if(...){
    A code.
}else if(...){
    B
    cCode();
}else if(...){
    cCode();
}else(...){
    D code.
}


private void cCode() {
   ...
}

答案 2 :(得分:0)

显然,其他两个答案更清晰,但只是抛出另一条路。

int condition = 2;
while(true) {
    if(condition == 1){
        System.out.println(1);

    }else if (condition == 2){
        System.out.println(2);
        condition = 3;
        continue;

    }else if (condition == 3){
        System.out.println(3);

    }

    break; //if continue gets called it will skip this
}