public class Clock {
int second;
int minute;
int hour;
boolean checkTime = true;
float startTime, endTime, difference;
public void time(){
if(checkTime){
startTime=System.currentTimeMillis();
checkTime=false;
}
endTime=System.currentTimeMillis(); // THIS ISN'T UPDATING, keeps the same
//value as start value each run through.
difference=endTime-startTime;
if(difference >= 1000){
second++;
checkTime = true;
}
}
public int getSecond(){
return second;
}
public int getMinute(){
return minute;
}
public int getHour(){
return hour;
}
public int getMs() {
return (int)difference;
}
}
这是我正在尝试创建的时钟类,以便跟踪时间。我有一个无限循环的主类,不断调用time();. void方法时间应该更新每次运行的时间,并且它拒绝更新endTime。 startTime将获得一个初始值,然后将相同的值一次又一次地赋予endTime。有人可以解释为什么会这样吗? *差异代表毫秒
答案 0 :(得分:2)
System.currentTimeMillis();
返回long
,您将其分配给endTime
,float
。使用long startTime, endTime, difference;
答案 1 :(得分:2)
float
只有6位精度。时间不会改变那么多,因为它是自1970年以来的时间。如果你原来使用long
,你应该看到它每毫秒都会改变。
float f = System.currentTimeMillis();
float f2 = Float.intBitsToFloat(Float.floatToRawIntBits(f) + 1);
System.out.println(f2 - f);
打印
131072.0
换句话说,分辨率只有两分多钟。
答案 2 :(得分:0)
因为您将startTime, endTime, difference
定义为浮点数
将它们定义为long
,它将被修复。