1- long xValue = someValue;
2- long 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,这就是程序在运行时因该异常而崩溃的原因,但是当我在线转换为什么转换不成功时。我认为编译器看到的类型已经很长了!
答案 0 :(得分:3)
这是不可能的
long xValue = someValue;
long yValue = someValue;
long otherTolalValue = (long)(xValue - yValue);
这三行中都不能产生java.lang.ClassCastException
假设someValues为Double,
Double someValue = 0.0;
它会给出编译错误:类型不匹配:无法将Double转换为long
答案 1 :(得分:2)
long xValue = (long)someValue;
// or :
long yValue = new Double(someValue).longValue();
long otherTolalValue = xValue - yValue;
但请记住,你会失去精确度。
答案 2 :(得分: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);
}
}
答案 3 :(得分:0)
据推测,someValue
是double
。要将其分配给long
,您需要将其投射:
long xValue = (long) someValue;