I am making a small alarm clock application to brush up on Java. The purpose of the app is to let the user set the clock time and alarm time, and then the alarm should “go off” when the system time is equal to the alarm time.
The clock class contains a Calendar and Date object.
The clock is referred to from a main method outside the class. In that main method, I have built a simple command line user interface, where the user can set the time of the clock and alarm. By default, the clock is initialized to the current system time.
However, here is where the problem is for both the automatically initialized and the user defined clock objects – they aren’t “ticking” or updating.
Clock regularClock = new Clock(); //Defaults clock (using a Date) to the system time
while (userInput != "Quit")
{
switch(userInput)
{
...Other choices here...
case "Set Time": System.out.print("Enter hour: ");
hours = kb.nextInt();
System.out.print("\nEnter minutes: ");
minutes = kb.nextInt();
ACR.regularClock.setTime(hours, minutes);
System.out.println("Clock has been set");
case "Set Alarm": System.out.print("Enter hour: ");
hours = kb.nextInt();
System.out.print("\nEnter minutes: ");
minutes = kb.nextInt();
ACR.alarmClock.setTime(hours, minutes);
ACR.alarmClock.setAlarmOn(true);
System.out.println("Alarm has been set.");
break;
...Other choices here...
userInput = keyboard.next();
}
As you will see, there are no loops or anything to refresh or keep the regularClock ticking. For some reason, when I started I thought Date and Calendar objects just kept running once created – sort of like a stopwatch.
So now I’m wondering what the best way to update them would be, in this while loop. If only the default system time clock was allowed, it would be easy – I could just create a new Date object at the beginning of the while loop each time. However, that would override the user created clock time if they chose that.
Also, if the user weren’t to enter any input – and instead just let the app sit there – where he/she would enter input – shouldn’t it still be refreshing the times and checking if the regularClock = alarmClock time? How can I do this?
I realize I’m sort of rambling now, so I’ll leave it at that. I’ve been working at this but can’t figure out the best solution. If you have any questions, please let me know!
Short summary questions:
-
How do I keep a the time in a Date or Calendar object ticking, even when it has been modified?
-
How can I continuously update these objects, while waiting for user input?
There are easier ways, but that’s not the question 😉
Basically, you need to establish some kind of “tick” thread that can update/modify the clock in the background…
You can write your own
Thread/Runnableto perform these tasks, but they are inherently inaccurate…Something like…
Beware though
Another way would be use the
java.util.TimerAgain, beware…