我是否在其他许多人之间有一个if子句是否重要?

ERJ*_*JAN -4 java if-statement

我刚发现一件令我困扰的事情让我困惑不解:

我有一个看起来像这样的方法:

if( condition1){}

else if(....){}

if(){} // this is confusing, does it matter if it becomes else if? 
       //Would the behavior change?

else if(){}
else if(){}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 7

当然重要.一个else if如果所有前述条件只计算if和else-如果条件相同的if-else-如果块都是假的.

一个if条件总是被评估,因为它开始一个新的if-else-if块.

您应该根据所需的逻辑在两者之间进行选择.

if( condition1){}

else if(....){} // this condition is only evaluated if all the preceding 
                // conditions were false

if(){} // this condition will be evaluated regardless of the result of 
       // evaluation the preceding conditions

else if(){}
else if(){}
Run Code Online (Sandbox Code Playgroud)