Java将双精度转换为长异常 [英] Java cast double to long exception

查看:62
本文介绍了Java将双精度转换为长异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1- long xValue = someValue;

1- long xValue = someValue;

2- long yValue = someValue;

2- long yValue = someValue;

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

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

该行代码给我以下异常:

That line of code give me the following exception:

java.lang.ClassCastException:java.lang.Double无法转换为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 包含双值,因为传递的图表具有数字类型但getYvalue()返回的时间很长,这就是为什么程序在运行时因该异常而崩溃,但是当我强制转换时为什么转换不成功。我认为编译器看到的类型已经很长了!

    seriesX1Data,seriesX2Data contains double values as the passed chart has Number type but getYvalue() return long that is why program crash at runtime with that exception but when i cast in line why cast not succeed. i think that compiler see that the type already long !.

    推荐答案

    不可能

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

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

    neither of the 3 lines can produce java.lang.ClassCastException

    假设someValue是Double,

    Assuming someValues is Double,

    Double someValue = 0.0;
    

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

    这篇关于Java将双精度转换为长异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆