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

时间:2015-09-16 06:00:44

标签: 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(){}

5 个答案:

答案 0 :(得分:7)

当然重要。仅当同一if-else-if块的所有前面的if和else-if条件都为假时,才会评估else if条件。

始终会评估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(){}

答案 1 :(得分:1)

if(condition1)
.
.
else if(....){}

在if之后if(),如果添加if(condition ..)语句,那么如果else阻塞它将被视为单独的。

答案 2 :(得分:1)

如果你的第三个if成为else-if,它将仅在第一个if-else if为假时进行评估

如果你这样离开,无论第一个if-else if是真还是假,都会被评估

答案 3 :(得分:1)

if else if块与switch块一样,只有一个区别,因为交换机直接跳转到与if else if块必须 R 每个条件到达特定的代码块。

if{}链之间插入另一个if else if块只会从新插入的if else if块中创建一个新的if块链。

答案 4 :(得分:1)

正如其他人所指出的,这很重要。但是如果它有所帮助,让我指出一个重要的事实:没有else if这样的东西!

else关键字后跟一个语句。有lots of kinds of statements:方法调用,值赋值......和块。

if (condition1)
  doSomething();
else
  doSomethingElse(); // a method invocation statement

// or...

if (condition2)
  doSomething();
else { // a block statement, which itself contains statements
  soSomethingElse();
  andAnotherThing();
}

这应该都很熟悉,但请考虑an if-else is itself a statement

// *all* of this is just a single statement, the if-else statement
if (condition3) {
   doYetAnotherThing();
} else {
   doEvenAnotherThing();
}

总而言之,else if实际上只是else,其声明本身就是if-else。以下完全等同于

// the syntax you're used to:
if (condition1) {
   doSomething();
} else if (condition2) {
   doAnotherThing();
} else {
   doAThirdThing();
}

// the same exact thing, written slightly more verbosely:
if (condition1) {
   doSomething();
} else {
  if (condition2) { // note that this if-else is within the else{...}
    doAnotherThing();
  } else {
    doAThirdThing();
  }
}

" if流中间的else-if开始了一个新的提问线。如果前面没有else,则之前的if只是一个普通的if,而不是if-else - 因此"嵌套"没有发生。

根据我发布的最后一个示例,并从else之前移除if (condition2),我们得到:

if (condition1) {
   doSomething();
} /*else*/ if (condition2) {
   doAnotherThing();
} else {
   doAThirdThing();
}

请注意,如果没有else到下一个else if(condition2),这就是它的样子,仅此而已。现在我们只需要使用略有不同的格式,逻辑就变得清晰了:

if (condition1) {
   doSomething();
}
if (condition2) {
   doAnotherThing();
} else {
   doAThirdThing();
}