java gregorian calendar timer
-
11-10-2019 - |
Question
I have this java program which calculates the time that the person took to respond to the confirm dialog box. But it seems that both time1 and time 2 gets the same value. What have I done wrong here:
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");
}
}
Solution
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");
}
}
OTHER TIPS
Why don't you use directly System.currentTimeMillis() ? eg:
long startAt = System.currentTimeMillis();
... your code ...
long elapsed = System.currentTimeMillis() - startAt;
CodegistCRest is right. but anyway in your case you will get the same or almost the same values. Modern computers are very fast but the time resolution you get from calendar and currentTimeMillis() is milliseconds. Computer invokes whole your program during less than 1 ms.
In real life you do not need all this. You have to say:
long before = System.currentTimeMillis();
when you are showing the dialog and
long after = System.currentTimeMillis();
as a part of action that is called when user pressed the button. Then say
time = after - before;