如果第一个为假,则一个 if 语句中的两个条件是否第二个重要?

好的,所以我测试了这段代码,我发现没有抛出任何异常.

Okay, so I have this piece of code tested and I found there isn't any exception thrown out.

public static void main(String[] args) {
    int[] list = {1,2};
    if (list.length>2 && list[3] == 2){
        System.out.println(list[1]);
    }
}

这里是不是声明

if (list.length>2 && list[3] == 2)

意味着如果第一个条件为假,我们甚至不必检查第二个条件?

mean that if the first condition is false we don't even have to check the second condition?

或者等于

if (list.length>2){
    if (list[3] == 2){
        ...
    }
}

?

而且,如果它是用 C 或 python 或其他一些语言编写的呢?

And, what if it is written in C or python or some other languages?

谢谢

推荐答案

在语言(Java 和 Python 等)中,对逻辑 AND 的第一个参数求值并完成对如果第一个参数是 false 的语句.这是因为:

It is common for languages (Java and Python are among them) to evaluate the first argument of a logical AND and finish evaluation of the statement if the first argument is false. This is because:

来自逻辑运算符的求值顺序,

当 Java 计算表达式 d = b &&c;,它首先检查 b 是否为真.这里 b 是假的,所以 b &&无论 c 是否为真,c 都必须为假,因此 Java 不会费心检查 c 的值.

When Java evaluates the expression d = b && c;, it first checks whether b is true. Here b is false, so b && c must be false regardless of whether c is or is not true, so Java doesn't bother checking the value of c.

这称为 短路评估,在Java 文档.

常见的是 list.count >0&&list[0] == "Something" 检查列表元素是否存在.

It is common to see list.count > 0 && list[0] == "Something" to check a list element, if it exists.

另外值得一提的是,if (list.length>2 && list[3] == 2) 不等于第二种情况

It is also worth mentioning that if (list.length>2 && list[3] == 2) is not equal to the second case

if (list.length>2){
    if (list[3] == 2){
        ...
    }
}

如果之后有 else.else 将仅适用于它所附加的 if 语句.

if there is an else afterwards. The else will apply only to the if statement to which it is attached.

为了演示这个问题:

if (x.kind.equals("Human")) {
    if (x.name.equals("Jordan")) {
        System.out.println("Hello Jordan!");
    }
} else {
    System.out.println("You are not a human!");
}

会按预期工作,但是

if (x.kind.equals("Human") && x.name.equals("Jordan")) {
    System.out.println("Hello Jordan!");
} else {
    System.out.println("You are not a human!");
}

还会告诉任何不是Jordan的人类他们不是人类.

will also tell any Human who isn't Jordan they are not human.

相关文章