在 if 语句中使用 == 运算符两次

发布于 2024-10-04 15:03:50 字数 175 浏览 7 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

べ繥欢鉨o。 2024-10-11 15:03:51

这是行不通的,因为 == 运算符是二进制的。
即使它按顺序工作,第一组也会返回一个布尔值,这不会对后面的整数起作用。

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.

全部不再 2024-10-11 15:03:51

不,它不会起作用,正如其他帖子中所解释的那样。但你可以做

if (turtles.get(h).getX() - turtles.get(g).getX() + 450 == 0) 

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) 
最偏执的依靠 2024-10-11 15:03:50

不。您预计那里会发生什么?

“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))?

方圜几里 2024-10-11 15:03:50

不,不是。这是因为 a == b 的结果是布尔值。如果你执行a == b == c,你首先会比较a == b,这将返回truefalse,然后将该真值与 c 进行比较。

通常不是您想做的事!

请注意,此技巧可以用于赋值,因为a = b的结果是ba的新值>) 这意味着 a = b = c 甚至 (a = b) == c 偶尔也会有用。

No, it's not. This is because the result of a == b is a boolean. 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.

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.

迷途知返 2024-10-11 15:03:50

不。它与 (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).

分开我的手 2024-10-11 15:03:50

或者使用辅助方法避免所有可读性较差(并且容易出错)的重复......

public boolean areEqual( int a, int b, int c )
{
    return ( a == b ) && ( b == c ) ;
}

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 ) ;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文