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

查看:794
本文介绍了一个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 <的第一个参数/ code>如果第一个参数是 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!");
}

还会告诉任何人不是约旦他们不是人。

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

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

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