java 键入将数字转换为双倍

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36557039/
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-11-03 01:35:27  来源:igfitidea点击:

Type casting a Number to double

javaandroidcasting

提问by Vishal Kinjavdekar

I am trying to compute few calculations for my project and I get following java.lang.ClassCastExceptionfor
y2= (double) molWt[x];

我试图计算少量计算为我的项目,我获得以下java.lang.ClassCastException
y2= (double) molWt[x];

molWtand distare two array of type Number and doublerespectively.

molWtdist分别是 Number 和 类型的两个数组 double

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

java.lang.ClassCastException: java.lang.Integer 不能转换为 java.lang.Double

public Double calcData(Number[] molWt, Double[] dist, String unk) {
        Double y2,y1, newY = null;
        Double x1,x2;

        Double unkn = Double.parseDouble(unk.toString());
        Double prev=0d;
        Double slope;


        for (int x = 0; x < dist.length; x++)
            if (unkn > prev && unkn < dist[x]) {
                y2 = (double) molWt[x];
                y1 = (double) molWt[x - 1];

                x2 = dist[x];
                x1 = dist[x - 1];

                slope = ((y2 - y1) / (x2 - x1));

                newY = slope * (unkn - x1) + y1;


            } else {
                prev = dist[x];
            }

        return newY;
    }

回答by Darth Android

Use Number.doubleValue():

使用Number.doubleValue()

y2 = molWt[x].doubleValue();

instead of trying to cast. Numbercannot be cast to a primitive double.

而不是尝试投射。Number不能强制转换为原始double.

回答by metin

you can use java.lang.Number.doubleValue() method to cast a number to a double object.

您可以使用 java.lang.Number.doubleValue() 方法将数字转换为双精度对象。

y2= molWt[x].doubleValue()

y2= molWt[x].doubleValue()