[英]Using the == operator twice in a if statement
Is it okay to do like this in java, does it work? 在Java中这样做是可以的吗?
if (turtles.get(h).getX() == turtles.get(g).getX() == 450) {
//stuff here
}
Basically, i want to check if X is the same value as Y and that value should be 450. 基本上,我想检查X是否与Y相同,并且该值应为450。
No. What do you expect to happen there? 否。您希望在那里发生什么?
"a == b" evaluates into a boolean, so "int == (int == int)" would evaluate into "int == boolean", and you cannot compare and int and a boolean. “ a == b”的计算结果为布尔值,因此“ int ==(int == int)”的计算结果为“ int == boolean”,因此您无法将int和布尔值进行比较。
Besides, what kind of logic are you trying to do here? 此外,您要在此处执行哪种逻辑?
if ((a == b) && (b == c))
? if ((a == b) && (b == c))
?
No, it's not. 不,这不对。 This is because the result of
a == b
is a boolean. 这是因为
a == b
的结果是布尔值。 If you do a == b == c
you are first comparing a == b
which will return true
or false
and then comparing that truth value to c
. 如果执行
a == b == c
,则首先比较a == b
,它将返回true
或false
,然后将该真值与c
进行比较。
Not what you want to do, usually! 通常不是您想做的!
Note that this trick can work for assignment because the result of a = b
is b
(the new value of a
) which means a = b = c
or even (a = b) == c
come in useful occasionally. 请注意,此技巧可以用于分配工作,因为结果
a = b
是b
(的新值a
),这意味着a = b = c
或甚至(a = b) == c
进来有用偶尔。
No. It is the same as (turtles.get(h).getX() == turtles.get(g).getX()) == 450 - "incomparable types". 不。它与(turtles.get(h).getX()== turtles.get(g).getX())== 450-“无与伦比的类型”相同。
if(turtles.get(h).getX() == 450 && turtles.get(g).getX() == 450)
. if(turtles.get(h).getX() == 450 && turtles.get(g).getX() == 450)
。
Or avoid all the less-readable (and error-prone) repetition with a helper method... 或者使用辅助方法避免所有不太可读(且容易出错)的重复...
public boolean areEqual( int a, int b, int c )
{
return ( a == b ) && ( b == c ) ;
}
That won't work, because the ==
operator is binary. 那是行不通的,因为
==
运算符是二进制的。
And even if it worked sequentially, the first set would return a boolean, which won't work against the integer that follows. 即使顺序执行,第一个集合也将返回一个布尔值,该布尔值不适用于随后的整数。
No it won't work, as explained in the other posts. 不,这是行不通的,如其他帖子所述。 But you could do
但是你可以做
if (turtles.get(h).getX() - turtles.get(g).getX() + 450 == 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.