Java cast double to long exception

两盒软妹~` 提交于 2019-12-12 09:16:55

问题


1- long xValue = someValue;

2- long yValue = someValue;

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

That line of code give me the following exception:

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

  • Update :

code piece:

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;
}
  • After debug i found that.

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 !.


回答1:


It's impossible

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

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

Assuming someValues is Double,

Double someValue = 0.0;

it would give compile error: Type mismatch: cannot convert Double to long




回答2:


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

long otherTolalValue = xValue - yValue;

But keep in mind that you will loose precision.




回答3:


I don't really understand why your code fail, but the following also works fine.

    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);
      }
   }



回答4:


Presumably someValue is a double. To assign it to a long you need to cast it:

long xValue = (long) someValue;


来源:https://stackoverflow.com/questions/15549076/java-cast-double-to-long-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!