eclipse Double 不会转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14088522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 19:42:49  来源:igfitidea点击:

Double is not converting to an int

javaeclipseintdouble

提问by Mayank Pratap

This code I have written to convert doubleinto intgetting an exception.

我编写的这段代码是为了转换doubleint获取异常。

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Cannot cast from Double to int

This is my code

这是我的代码

Double d = 10.9;    
int i = (int)(d);

回答by dasblinkenlight

Doubleis a wrapperclass on top of the primitive double. It can be cast to double, but it cannot be cast to intdirectly.

Double是基元之上的包装double。它可以转换为double,但不能int直接转换为 。

If you use doubleinstead of Double, it will compile:

如果使用double而不是Double,它将编译:

double d = 10.9;    
int i = (int)(d); 

You can also add a cast to doublein the middle, like this:

您还可以double在中间添加演员表,如下所示:

int i = (int)((double)d); 

回答by radai

thats because you cant mix unboxing (converting your Doubleto a double primitive) and casting. try

那是因为你不能混合拆箱(将你的转换Double为双primitive)和铸造。尝试

int i = (int)(d.doubleValue());

回答by Sri Harsha Chilakapati

This

这个

Double d = 10.9;

is your error. You are using wrapper classes instead of data types. Use

是你的错误。您正在使用包装类而不是数据类型。用

double d = 10.9;

回答by Avinash T.

You can not cast wrapper like Double to primitive type like int directly.

您不能将像 Double 这样的包装器直接转换为像 int 这样的原始类型。

You can try this -

你可以试试这个——

int i = (int)((double)d);

int i = (int)((double)d);

For more check following link - http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

有关更多检查以下链接 - http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html