I'm getting ridiculous results in my program!
Seconds work fine
Decaseconds (1/10 of a second) work ok
Centiseconds seem a bit off
Milliseconds are completely off...
Here's the code--
import javax.swing.*;
import java.awt.event.*;
public class Clock{
private Timer t;
private long startTime = 0, finishTime = 0;
private boolean isStarted = false;
public static final int SECONDS = 0, DECASECONDS = 1, CENTISECONDS = 2, MILLISECONDS = 3;
public Clock(int timeType){
switch(timeType){
case 0: t = new Timer(1000, al);
break;
case 1: t = new Timer(100, al);
break;
case 2: t = new Timer(10, al);
break;
case 3: t = new Timer(1, al);
break;
default: t = new Timer(1000, al);
break;
}
}
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent e){
finishTime++;
}
};
public synchronized void start(){
if(!isStarted){
isStarted = true;
startTime = finishTime;
t.start();
}
}
public synchronized void finish(){
if(isStarted){
isStarted = false;
t.stop();
}
}
public synchronized long getTimeElapsed(){
return finishTime - startTime;
}
public synchronized long getCurrentStart(){
return startTime;
}
public synchronized long getCurrentFinish(){
return finishTime;
}
public synchronized void resetTimer(){
if(!isStarted){
startTime = 0;
finishTime = 0;
}else JOptionPane.showMessageDialog(null, "Please stop the clock before trying to reset it.");
}
}
public class DriverProgram_3{
public static void main(String... args){
Clock c = new Clock(Clock.SECONDS);
c.start();
lengthyMethod();
c.finish();
System.out.println("Nethod lengthyMethod took " + c.getTimeElapsed() + " seconds to finish execution.");
}
public static void lengthyMethod(){
for(long i = 0; i < 1000000000; i++);
}
}
Was my approach wrong?