问题描述
我正在尝试编写一个获取 double
的方法,验证该数字是否在点之后有一些内容,如果有,则返回 double
,如果没有 - 返回 int
。
I'm trying to write a method which gets a double
, verifies if the number has something after the dot and if it does—returns a double
, if doesn't—returns an int
.
public class Solution {
public static void main(String[] args) {
double d = 3.000000000;
System.out.println(convert1(d));
System.out.println(convert2(d));
}
static Object convert1(double d) {
if(d % 1 == 0)
return (int) d;
else
return d;
}
static Object convert2(double d) {
return ((d%1) == 0) ? ((int) (d)) : d;
}
}
输出:
3
3.0
所以,我想要的一切都发生在方法 convert1()
中,但不会发生在方法 convert2()
中。看来这些方法必须做同样的工作。但我做错了什么?
So, everything I want happens in method convert1()
, but doesn't happen in method convert2()
. It seems as these methods must do the same work. But what I have done wrong?
推荐答案
正如其他答案所述,这种行为是因为三元表达式的两种可能结果必须具有相同的类型。
As the other answers have stated, this behavior is because both possible results of a ternary expression must have the same type.
因此,您需要做的就是使您的三元版本与 convert1()
的工作方式相同将 int
转换为对象
:
Therefore, all you have to do to make your ternary version work the same way as convert1()
is to cast the int
to an Object
:
static Object convert2(double d) {
return ((d % 1) == 0) ? ((Object) (int) (d)) : d;
}
这篇关于由三元运算符产生的意外类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!