Can't Get Timer to Work, What Am I doing Wrong?!?!
I'm trying to make a program where you enter the amount of minutes you want to time and when it's done it will tell you the timer is done. Here's the code
Code :
import javax.swing.JOptionPane;
//1 minute = 60,000 milliseconds
public class Main {
String input;
long timer;
long startTime;
long currentTime;
long endTime;
public void start(){
input = JOptionPane.showInputDialog("Enter the amount of minutes you want to time");
timer = Long.parseLong(input);
timer = timer*60000;
startTime = System.currentTimeMillis();
System.out.println(startTime);
timer();
}
public void timer(){
while(true){
currentTime = System.currentTimeMillis();
endTime = startTime+timer;
startTime++;
if(currentTime == endTime){
takeBreak();
}
}
}
public void takeBreak(){
JOptionPane.showMessageDialog(null, "Timer Finished");
System.exit(0);
}
public static void main(String[] args){
Main main = new Main();
main.start();
}
}
Re: Can't Get Timer to Work, What Am I doing Wrong?!?!
What happens when you execute the code?
Can you explain the problem?
Re: Can't Get Timer to Work, What Am I doing Wrong?!?!
When I run it the timer never ends, is my code good?
Re: Can't Get Timer to Work, What Am I doing Wrong?!?!
You need to try debugging the code to see what it is doing. Add a println statement inside the while loop that prints out the values of currentTime and endTime just before the if statement so you can see what their values are as the code executes.
For testing:
I suggest you remove the *60000 and just use the value entered for the duration to make the numbers more reasonable.
Also I recommend that you replace the while(true) loop with a for loop that goes for 100 loops.
That will be enough times that the print out will show you what the problem is.
Another suggestion: Don't use an == test for the end time,
better to use >=
BTW This is the absolute worst way to have a program wait.
The Thread class's sleep() method is one better way. Later you find some other better ways.
I'm Done for tonight. Back tomorrow.