问题
This code I have written to convert double into int getting an exception.
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);
回答1:
Double is a wrapper class on top of the primitive double. It can be cast to double, but it cannot be cast to int directly.
If you use double instead of Double, it will compile:
double d = 10.9;
int i = (int)(d);
You can also add a cast to double in the middle, like this:
int i = (int)((double)d);
回答2:
thats because you cant mix unboxing (converting your Double to a double primitive) and casting.
try
int i = (int)(d.doubleValue());
回答3:
This
Double d = 10.9;
is your error. You are using wrapper classes instead of data types. Use
double d = 10.9;
回答4:
You can not cast wrapper like Double to primitive type like int directly.
You can try this -
int i = (int)((double)d);
For more check following link - http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
来源:https://stackoverflow.com/questions/14088522/double-is-not-converting-to-an-int