多个'if'语句和'if-else-if'语句对于互斥条件是否相同?

Are multiple 'if' statements and 'if-else-if' statements the same for mutually exclusive conditions?

写多个if语句和if-else-if语句有什么区别吗?

当我尝试用多个 if 语句编写程序时,它没有给出预期的结果,但它与 if-else-if.

一起工作

条件互斥。

不,两者不一样。 if 语句将检查所有条件。如果您将编写多个 if 语句,它将检查每个条件。 If else 将检查条件,直到满足为止。一旦 if/else 如果满足,它将离开该块。

当您编写多个 if 语句时,可能会有多个 if 语句被评估为 true,因为这些语句彼此独立。

当您编写单个 if else-if else-if ... else 语句时,只能将一个条件计算为真(一旦找到计算结果为真的第一个条件,则下一个 else-if 条件为跳过)。

如果每个条件块都跳出包含 if 语句的块(例如,通过 returning从方法或从循环中断)。

例如:

public void foo (int x)
{
    if (x>7) {
        ...
        return;
    }
    if (x>5) {
        ...
        return;
    }    
}

将具有与 :

相同的行为
public void foo (int x)
{
    if (x>7) {
        ...
    }
    else if (x>5) {
        ...
    }
}

但是如果没有 return 语句,当 x>5 和 x>7 都为真时,它会有不同的行为。

是的,这很重要:参见 The if-then and if-then-else Statements

此外,您可以轻松测试它。

代码#1:

    int someValue = 10;

    if(someValue > 0){
        System.out.println("someValue > 0");
    }

    if(someValue > 5){
        System.out.println("someValue > 5");
    }

将输出:

someValue > 0
someValue > 5

代码 #2:

    int someValue = 10;

    if(someValue > 0){
        System.out.println("someValue > 0");
    }else if(someValue > 5){
        System.out.println("someValue > 5");
    }

只会输出:

someValue > 0

如您所见,代码 #2 永远不会进入第二个块,因为第一个语句 (someValue > 0) 的计算结果为 true.

if()
{
stmt..
}
else
{
stmt
}
if()
{
stmt
}
here compiler will check for both the if condition.

在下面的代码片段中,编译器将检查 if 条件,一旦第一个 if 条件为真,剩下的 if 条件将被绕过。

        if(){

        }
        else if
        {

        }
        else if
        {

        }
        else if
        {

        }