我有这个java程序,它计算人员响应确认对话框所花费的时间。但似乎time1和time2都得到相同的值。我在这里做错了什么:
import javax.swing.JOptionPane;
import java.util.*;
public class DialogTimer{
public static void main(String args[]){
int time1, time2, milli1, milli2, sec1, sec2, timeDifference;
final int MILLISECSINSECOND =1000;
JOptionPane.showConfirmDialog(null, "Is stealing ever justified? ");
GregorianCalendar before=new GregorianCalendar();
GregorianCalendar after= new GregorianCalendar();
milli1=before.get(GregorianCalendar.MILLISECOND);
milli2=after.get(GregorianCalendar.MILLISECOND);
sec1=before.get(GregorianCalendar.SECOND);
sec2=after.get(GregorianCalendar.SECOND);
time1=MILLISECSINSECOND * sec1 + milli1;
time2=MILLISECSINSECOND * sec2 + milli2;
//timeDifference=time1 - time2;
System.out.println(time1);
System.out.println(time2);
//JOptionPane.showMessageDialog(null, "It took " + (time1 - time2) + " milliseconds for you to answer");
}
}
答案 0 :(得分:4)
为什么不直接使用System.currentTimeMillis()?例如:
long startAt = System.currentTimeMillis();
... your code ...
long elapsed = System.currentTimeMillis() - startAt;
答案 1 :(得分:2)
import javax.swing.JOptionPane;
import java.util.*;
public class DialogTimer{
public static void main(String args[]){
int time1, time2, milli1, milli2, sec1, sec2, timeDifference;
final int MILLISECSINSECOND =1000;
GregorianCalendar before=new GregorianCalendar();
milli1=before.get(GregorianCalendar.MILLISECOND);
JOptionPane.showConfirmDialog(null, "Is stealing ever justified? ");
GregorianCalendar after= new GregorianCalendar();
milli2=after.get(GregorianCalendar.MILLISECOND);
sec1=before.get(GregorianCalendar.SECOND);
sec2=after.get(GregorianCalendar.SECOND);
time1=MILLISECSINSECOND * sec1 + milli1;
time2=MILLISECSINSECOND * sec2 + milli2;
//timeDifference=time1 - time2;
System.out.println(time1);
System.out.println(time2);
//JOptionPane.showMessageDialog(null, "It took " + (time1 - time2) + " milliseconds for you to answer");
}
}
答案 2 :(得分:1)
CodegistCRest是对的。但无论如何,在你的情况下,你会得到相同或几乎相同的值。现代计算机非常快,但从calendar和currentTimeMillis()获得的时间分辨率是毫秒。计算机在不到1毫秒的时间内调用整个程序。
在现实生活中,你不需要这一切。你必须说:
long before = System.currentTimeMillis();
当您显示对话框并
时 long after = System.currentTimeMillis();
作为用户按下按钮时调用的操作的一部分。然后说
time = after - before;