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;
}
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.
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.
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 .
Use Number.doubleValue():
y2 = molWt[x].doubleValue();
instead of trying to cast. Number
cannot be cast to a primitive double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With