我正在解决一个问题,我不明白为什么它不起作用。如何通过 double obj
传递变量并转换为 int
?
为什么它在顶部代码片段中不起作用,但在该行下方的底部代码片段中起作用?
唯一的区别似乎是添加了一个额外的变量,它的类型也为 double
?
//Converting double to int using helper
//This doesn't work- gets error message
//Cannot invoke intValue() on the primitive type double
double doublehelpermethod = 123.65;
double doubleObj = new Double( doublehelpermethod);
System.out.println("The double value is: "+ doublehelpermethod.intValue());
//--------------------------------------------------------------------------
//but this works! Why?
Double d = new Double(123.65);
System.out.println("The double object is: "+ doubleObj);
最佳答案
double
是原始类型,而 Double
是常规 Java 类。您不能调用原始类型的方法。然而,intValue()
方法在 Double
上可用,如 javadoc 中所示。
关于这些基本类型的更多阅读可以找到 here
关于java - Object.intValue() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631652/