为什么带有赋值和等式检查的if语句的计算结果为false? [英] Why does this if statement, with an assignment and equality check, evaluate to false?
问题描述
Java if语句如何在具有赋值和相等性检查时工作或
-d在一起??
How does a Java if statement work when it has an assignment and an equality check OR
-d together??
public static void test() {
boolean test1 = true;
if (test1 = false || test1 == false) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
为什么打印错误?
推荐答案
表达式不会按您的想法解析。它不是
The expression is not parsed the way you think. It's not
(test1=false) || (test1 == false)
在这种情况下,结果将是 true
,但是
in which case the result would have been true
, but
test1 = (false || test1 == false)
false ||的值test1 == false
表达式首先计算,它是 false
,因为 test1
是设置为 true
进入计算。
The value of false || test1 == false
expression is computed first, and it is false
, because test1
is set to true
going into the computation.
以这种方式解析它的原因是 || 的http://introcs.cs.princeton.edu/java/11precedence/\">precedence 低于 ==
运算符,但高于赋值运算符的优先级 =
。
The reason it is parsed this way is that the precedence of the ||
is lower than that of the ==
operator, but higher than the precedence of the assignment operator =
.
这篇关于为什么带有赋值和等式检查的if语句的计算结果为false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!