Java - 三元运算符奇怪的行为 [英] Java - ternary operator weird behaviour

查看:153
本文介绍了Java - 三元运算符奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从 double 中移除小数部分,以防它全部使用:

I was trying to remove the fractional part from a double in case it is whole using:

(d % 1) == 0 ? d.intValue() : d

并遇到以下我不明白的行为:

And encountered the following behavior which i don't understand:

public static void main(String[] args) {
    Double d = 5D;
    System.out.println((d % 1) == 0);                               // true
    System.out.println((d % 1) == 0 ? d.intValue() : "not whole");  // 5
    System.out.println((d % 1) == 0 ? d.intValue() : d);            // 5.0
}

正如您在第三行所看到的,运营商选择了 else value - 5.0 即使条件(d%1)== 0

As you can see on the third line, the operator chooses the else value - 5.0 even though the condition (d % 1) == 0 is met.

这里发生了什么?

推荐答案

三元条件运算符的返回类型必须是第二个和第三个操作数都可以分配给它。

The return type of the ternary conditional operator must be such that both the 2nd and 3rd operands can be assigned to it.

因此,在第二种情况下,运算符的返回类型是 Object (因为 d.intValue()不是整个必须可以分配给它,而在第三种情况下它是 Double (因为两者都是 d.intValue() d 必须可分配给它)。

Therefore, in your second case, the return type of the operator is Object (since both d.intValue() and "not whole" must be assignable to it) while in the third case it is Double (since both d.intValue() and d must be assignable to it).

打印对象,其运行时类型为整数给出你 5 打印 Double 给你 5.0

Printing an Object whose runtime type is Integer gives you 5 while printing a Double gives you 5.0.

这篇关于Java - 三元运算符奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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