Java转换为double to longexception

1- long xValue = someValue;

2- long yValue = someValue;

3- long otherTolalValue =(long)(xValue – yValue);

那行代码给了我以下exception:

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

  • 更新:

代码片:

 StackedBarChart sbc = new StackedBarChart(); XYChart.Series series = new XYChart.Series(); series.getData.add(new XYChart.Data("X1",150)); series.getData.add(new XYChart.Data("X2",50)); sbc.getData.add(series); long dif = getDif(sbc); long getDif(XYChart barChart){ XYChart.Series series = (XYChart.Series).getData().get(0); // X1 at zero position i dont have to use iIterator now. XYChart.Data seriesX1Data = series.getData().get(0); XYChart.Data seriesX2Data = series.getData().get(1); long x1Value = seriesX1Data.getYValue(); long x2Value = seriesX1Data.getYValue(); // line - 3 - exception on the next line // -4- long value = (x1Value) - (x2Value); long value = (long)(x1Value) - (long)(x2Value); return value; } 
  • 调试后我发现了。

seriesX1Data,seriesX2Data包含double值, as the passed chart has Number type但是getYvalue()返回long,这就是程序在运行时因该exception而崩溃的原因,但是当我在行中抛出为什么转换不成功时。 我认为编译器看到的类型已经很长了!

不可能

 long xValue = someValue; long yValue = someValue; long otherTolalValue = (long)(xValue - yValue); 

3行中的任何一行都不能产生java.lang.ClassCastException

假设someValues是Double,

 Double someValue = 0.0; 

它会给出编译错误: 类型不匹配:无法将Double转换为long

 long xValue = (long)someValue; // or : long yValue = new Double(someValue).longValue(); long otherTolalValue = xValue - yValue; 

但请记住,你会失去精确度。

我真的不明白为什么你的代码失败,但以下也可以正常工作。

  public class CastingDoubleToLongTest { @Test public void testCast(){ double xValue = 12.457; double yValue = 9.14; long diff = new Double(xValue - yValue).longValue(); Assert.assertEquals(3, diff); } } 

据推测, someValuedouble 。 要将它指定为long您需要将其强制转换:

 long xValue = (long) someValue;