Java-程序isn';t更新系统.currentTimeMillis()
这是我的时钟类,我正试图创建它来跟踪时间。我有一个主类,它处于一个无止境的循环中,不断地调用time();。void方法time应该更新每次运行的时间,它拒绝更新endTime。startTime将获得一个初始值,然后相同的值将一次又一次地提供给endTime。有人能解释为什么会发生这种情况吗*差异表示毫秒Java-程序isn';t更新系统.currentTimeMillis(),java,Java,这是我的时钟类,我正试图创建它来跟踪时间。我有一个主类,它处于一个无止境的循环中,不断地调用time();。void方法time应该更新每次运行的时间,它拒绝更新endTime。startTime将获得一个初始值,然后相同的值将一次又一次地提供给endTime。有人能解释为什么会发生这种情况吗*差异表示毫秒System.currentTimeMillis()返回一个long,您将其分配给endTime,一个float。使用long startTime、endTime、difference系统.c
System.currentTimeMillis()
返回一个long
,您将其分配给endTime
,一个float
。使用long startTime、endTime、difference代码>系统.currentTimeMillis()
返回一个long
,您将其分配给endTime
,一个float
。使用long startTime、endTime、difference
浮点
只有6位精度。自1970年以来,时间变化不大。如果您使用的long
与原来一样,您应该会看到它每毫秒都会发生变化
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;
}
}
印刷品
float f = System.currentTimeMillis();
float f2 = Float.intBitsToFloat(Float.floatToRawIntBits(f) + 1);
System.out.println(f2 - f);
换句话说,分辨率只有两分钟多一点。
float
只有6位精度。自1970年以来,时间变化不大。如果您使用的long
与原来一样,您应该会看到它每毫秒都会发生变化
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;
}
}
印刷品
float f = System.currentTimeMillis();
float f2 = Float.intBitsToFloat(Float.floatToRawIntBits(f) + 1);
System.out.println(f2 - f);
换句话说,分辨率只有两分钟多一点。因为您将
开始时间、结束时间、差异定义为浮动。
将它们定义为long
,它将是固定的。因为您将startTime、endTime、difference
定义为浮动。
将它们定义为long
,它将被修复。对我来说很好。你只是不明白为什么它会显示像1.39345933E12
?对我来说很好。您只是不明白为什么它会显示类似于1.39345933E12
?