一个 if 语句中的两个条件如果第一个为假,第二个是否重要? [英] Two conditions in one if statement does the second matter if the first is false?

查看:64
本文介绍了一个 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) not 等于第二种情况

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.

这篇关于一个 if 语句中的两个条件如果第一个为假,第二个是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆