Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting a Number to double

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

molWt and dist are two array of type Number and double respectively.

java.lang.ClassCastException: java.lang.Integer cannot be cast to 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;
    }
like image 360
Vishal Kinjavdekar Avatar asked Apr 11 '16 18:04

Vishal Kinjavdekar


People also ask

Can you cast an int to a double?

Since double has longer range than int data type, java automatically converts int value to double when the int value is assigned to double. 1. Java implicit conversion from int to double without typecasting.

How do you cast to a double Java?

In Java when you cast you are changing the “shape” (or type) of the variable. The casting operators (int) and (double) are used right next to a number or variable to create a temporary value converted to a different data type. For example, (double) 1/3 will give a double result instead of an int one.

Can you cast int to double in C?

The %d format specifier expects an int argument, but you're passing a double . Using the wrong format specifier invokes undefined behavior. To print a double , use %f .


1 Answers

Use Number.doubleValue():

y2 = molWt[x].doubleValue();

instead of trying to cast. Number cannot be cast to a primitive double.

like image 127
Darth Android Avatar answered Sep 17 '22 00:09

Darth Android