【发布时间】:2013-09-26 08:11:58
【问题描述】:
我有两种类似的方法,但它们的工作方式略有不同。 注意: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,效果很好(eg:300.0)
public float getCurrentSpeed() throws IOException
{
long KBytesDownloaded = this.getBytesDownloaded() / 1024;
currentTime = System.currentTimeMillis();
float speed = KBytesDownloaded * 1000 / (currentTime - startTime));
return speed;
}
为什么两个相似的方法不返回相同的类型值?谢谢。
【问题讨论】:
-
“不返回任何值”是什么意思?
-
除非抛出异常,否则该方法不可能不“返回任何值”,在这种情况下,您应该发布堆栈跟踪。你的意思是它返回零?
-
对不起,我忘记了错误:线程“Timer-0”中的异常 java.lang.NoSuchMethodError: com.myclasses.Downloa d.getCurrentSpeed()F at test$2.run(test.java: 87) 在 java.util.TimerThread.mainLoop(Timer.java:555) 在 java.util.TimerThread.run(Timer.java:505)
-
天哪。这只是意味着您需要重新编译所有内容。与这里的代码无关。
-
@user1780606 您的实现中仍然出现截断错误。
1000和(currentTime - startTime)都不是float,因此它们的除法将产生截断的Long值(不精确)。查看stackoverflow.com/a/19022838/1433665
标签: java int long-integer