Java - 关于float,long,int

时间:2013-09-26 08:11:58

标签: java int long-integer

我有两种类似的方法,但它们的工作方式不同。 注意:getBytesDownloaded(),getFileSize()返回long。

此方法完全返回我期望的整数值(例如:51)

public int getPercentComplete() throws IOException
    {
        int complete = (int) Math.round(this.getBytesDownloaded()*100 / this.getFileSize());
        return complete;
    }

但是这个方法在运行时不会返回任何值(即使我将int更改为long),尽管编译好了:

public int getCurrentSpeed() throws IOException
{
    long KBytesDownloaded = this.getBytesDownloaded() / 1024;
    currentTime = System.currentTimeMillis();
    int speed =  (int) Math.round(KBytesDownloaded * 1000 / (currentTime - startTime));
    return speed;
}

错误:

Exception in thread "Timer-0" java.lang.NoSuchMethodError: com.myclasses.Downloa
d.getCurrentSpeed()F
        at test$2.run(test.java:87)
        at java.util.TimerThread.mainLoop(Timer.java:555)
        at java.util.TimerThread.run(Timer.java:505)

要解决这个问题,我将int更改为float,它工作正常(例如:300.0)

public float getCurrentSpeed() throws IOException
    {
        long KBytesDownloaded = this.getBytesDownloaded() / 1024;
        currentTime = System.currentTimeMillis();
        float speed =  KBytesDownloaded * 1000 / (currentTime - startTime));
        return speed;
    }

为什么两个类似的方法不返回相同的类型值?谢谢。

3 个答案:

答案 0 :(得分:1)

当您在类中调用方法时会抛出NoSuchMethodError,但该类没有该方法。当您已经有一个已编译的程序,然后在一个类中更改方法声明而不重新编译依赖它的类时,就会发生这种情况。

在这种情况下,您的test课程已编译为在float getCurrentSpeed()课程中调用Download。然后,您将方法返回类型更改为int,而不重新编译test类,因此test所需的方法不再存在,因此NoSuchMethodError。当您将返回类型更改回float时,问题就消失了。

如果您更改Download中的返回类型,请不要忘记重新编译test

答案 1 :(得分:0)

我用一些随机的int,long和double变量测试了你的代码。

即使我没有尝试过很多测试用例,

他们似乎对我都很好。

你是什么意思,它没有返回任何价值?

=============================================== ===

如果是无方法错误,请重新编译并再次运行。

如果这样做无效,请检查您是否正在调用正确的功能

答案 2 :(得分:-1)

Math.round()floatdouble作为参数。

KBytesDownloaded * 1000 / (currentTime - startTime)

在此表达式中,KBytesDownloadedLong

问题是像Long/Long这样的除法会截断小数点后的浮点值。

确保在转换为floatdouble之前输入强制转换以防止截断。

 int speed =  Math.round(KBytesDownloaded * (float) 1000 / (currentTime - startTime));
相关问题