在 if 语句中使用 == 运算符两次
在java中这样做可以吗,行得通吗?
if (turtles.get(h).getX() == turtles.get(g).getX() == 450) {
//stuff here
}
基本上,我想检查 X 是否与 Y 的值相同,并且该值应该是 450。
Is it okay to do like this in java, does it work?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是行不通的,因为
==
运算符是二进制的。即使它按顺序工作,第一组也会返回一个布尔值,这不会对后面的整数起作用。
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
不。您预计那里会发生什么?
“a == b”计算为布尔值,因此“int == (int == int)”将计算为“int == boolean”,并且您不能比较 int 和布尔值。
另外,你想在这里做什么逻辑?
if ((a == b) && (b == c))
?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.
Besides, what kind of logic are you trying to do here?
if ((a == b) && (b == c))
?不,不是。这是因为
a == b
的结果是布尔值。如果你执行a == b == c
,你首先会比较a == b
,这将返回true
或false,然后将该真值与
c
进行比较。通常不是您想做的事!
请注意,此技巧可以用于赋值,因为
a = b
的结果是b
(a
的新值>) 这意味着a = b = c
甚至(a = b) == c
偶尔也会有用。No, it's not. This is because the result of
a == b
is a boolean. If you doa == b == c
you are first comparinga == b
which will returntrue
orfalse
and then comparing that truth value toc
.Not what you want to do, usually!
Note that this trick can work for assignment because the result of
a = b
isb
(the new value ofa
) which meansa = b = c
or even(a = b) == c
come in useful occasionally.不。它与 (turtles.get(h).getX() ==turtles.get(g).getX()) == 450 - “不可比较类型”相同。
if(turtles.get(h).getX() == 450 &&turtles.get(g).getX() == 450)
。No. It is the same as (turtles.get(h).getX() == turtles.get(g).getX()) == 450 - "incomparable types".
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...