2
votes

I have written a java code for scientific calculator and also written jUnit test for it.Below is the method for calculating cubeRoot.

public <T> Double cubeRoot(T number){
    Double result= Math.cbrt((Double)number);
    return Math.abs(result);
}

Method returns proper result integer and double types,but when i invoke method for decimal,argument i pass is double type.Following are the JUint Test for above method.

public void testCalculateCubeRootWhenNegative(){
    Integer number=-64;
    assertEquals(-4.0,sci.cubeRoot(number));
}

public void testCalculateCubeRootOfdecimal(){
    Double number=0.40;
    assertEquals(0.736,sci.cubeRoot(number));
}

And this the interface i am using

public interface iScientific extends iMaths {
<T>Double squareRoot(T number);

<T>Double cubeRoot(T number);

Unable to find solution for getting error "java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double"

2

2 Answers

5
votes

You are trying do to something like this:

Integer i = Integer.valueOf(0);
Double d = (Double) i;

This does not work because i is not an instance of Double.

I suggest to change your cubeRoot method to accept a Number (the base class of both Integer and Double):

public Double cubeRoot(Number number) {
  Double result = Math.cbrt(number.doubleValue());
  return Math.abs(result);
}
-1
votes

Again i have do some more code change to make the code error free as initially error persist.Check the correction i have made and do suggest for more refactoring of code.

public Double cubeRoot(Number number){
    DecimalFormat df=new DecimalFormat("#.####");
    double result= Math.cbrt(number.doubleValue());
    return Double.valueOf(df.format(result));
}

And the following test passed.

public void testCalculateCubeRootWhenNegative(){
    Integer number=-64;
    assertEquals(-4.0,sci.cubeRoot(number));
}
public void testCalculateCubeRootOfdecimal(){
    Double number=0.40;
    assertEquals(0.7368,sci.cubeRoot(number));
}