1

1- 长 xValue = someValue;

2- 长 yValue = someValue;

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

那行代码给了我以下异常:

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

  • 更新 :

代码段:

StackedBarChart<String,Number> sbc = new StackedBarChart<String,Number>();

XYChart.Series<String, Number> series = new XYChart.Series<String, Long>();
series.getData.add(new XYChart.Data<String, Number>("X1",150));
series.getData.add(new XYChart.Data<String, Number>("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<String, Long> seriesX1Data = series.getData().get(0);
XYChart.Data<String, Long> 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包含双精度值as the passed chart has Number type,但 getYvalue() 返回 long,这就是为什么程序在运行时崩溃并出现该异常,但是当我在线投射时,为什么投射不成功。我认为编译器看到该类型已经很长了!

4

4 回答 4

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

long otherTolalValue = xValue - yValue;

但请记住,您将失去精度。

于 2013-03-21T13:37:36.677 回答
2

不可能

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

3 行都不能产生 java.lang.ClassCastException

假设 someValues 是 Double,

Double someValue = 0.0;

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

于 2013-03-21T14:02:58.723 回答
1

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

    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);
      }
   }
于 2013-03-21T14:08:41.367 回答
0

大概someValue是一个double。要将其分配给long您需要转换它:

long xValue = (long) someValue;
于 2013-03-21T14:05:27.070 回答