【问题标题】:Double is not converting to an intDouble 没有转换为 int
【发布时间】:2012-12-14 20:11:10
【问题描述】:

我编写的这段代码将double 转换为int 得到一个异常。

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

这是我的代码

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

【问题讨论】:

    标签: java eclipse int double


    【解决方案1】:

    Double 是基本 double 之上的 wrapper 类。可以转换为double,但不能直接转换为int

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

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

    你也可以在中间给double添加演员表,像这样:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 错字convertign 不见了。
      【解决方案3】:

      这个

      Double d = 10.9;
      

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

      double d = 10.9;
      

      【讨论】:

        【解决方案4】:

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

        你可以试试这个-

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

        欲了解更多信息,请查看以下链接 - http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

        【讨论】:

        • You can not cast wrapper like Double to primitive type like int directly.并非总是(double) new Integer(5); 会起作用。
        猜你喜欢
        • 2011-05-10
        • 1970-01-01
        • 2014-08-15
        • 2020-04-05
        • 2013-06-02
        • 1970-01-01
        • 2019-02-19
        • 2012-09-02
        相关资源
        最近更新 更多