简体   繁体   English

简化Java中复杂的if语句

[英]Simplify the complex if statements in java

Is there a way to simplyfy the below code, I can combine condition1 and condition2 but I want the else statements print different messages for each step. 有没有一种方法可以简单地完成以下代码,我可以将condition1和condition2组合在一起,但是我希望else语句为每个步骤打印不同的消息。

if(condition1){
    if(condition2){
        if(condition3){
            //do something
        }
    }
    else{
       //sout condition2 failed
    }
}
else{
    //sout condition1 failed
}

the simplest i could come up with is 我能想到的最简单的是

if(condition1 && condition2 && condition3){
    //do something
}
else if(!condition1){
    //sout condition1 failed
}
else if(!condition2){
    //sout condition2 failed
}

The simplest is to flip conditions 1 and 2, so it becomes an if-elseif construct, which doesn't require deeply nested blocks: 最简单的是翻转条件1和2,因此它变成了if-elseif构造,不需要深度嵌套的块:

if (! condition1) {
    //sout condition1 failed
} else if (! condition2) {
    //sout condition2 failed
} else if (condition3) {
    //do something
}

If you also wanted else block for condition3 (missing in question code), flip condition 3 too. 如果您还希望else阻止condition3 (问题代码缺失),也可以翻转条件3。

if (! condition1) {
    //sout condition1 failed
} else if (! condition2) {
    //sout condition2 failed
} else if (! condition3) {
    //sout condition3 failed
} else {
    //do something
}

merge condition 2 and 3 合并条件2和3

if(condition1){
    if(condition2 && condition3){
       //do something
    }
    else if (!condition2){
       //sout condition2 failed
    }
}
else {
    //sout condition1 failed
}

You can also check the false condition first like 您也可以先检查错误状况,例如

if(!condition1){

    //sout condition1 failed

} else if(!condition2){

    //sout condition2 failed

} else if(condition3){
  //do something
}
if(condition1 && condition2 && condition3){
    //do something
 }

 String failed = !condition1? "condition1 failed":
                 !condition2? "condition2 failed" : "";

 System.out.println(failed);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM