package class6_3_ObjectOrientedProgramming; // MSOE. Dr. Yoder. 07 October 2015. import java.text.DecimalFormat; /** * Models a real-world clock on the wall. */ public class Clock { public static final int MINUTES_TOP_OF_CLOCK = 60; /** * The minute part of the time (minutes past the hour). In the range 0-59. */ private int minutes; /** * The hour part of the time. In the range 1-12. */ private int hours; public final int SLEEP_TIME_MILLISECONDS = 1000; /** * Set the clock to the specified time. * @param hrs the hour part of the time. Must be in the range 1-12. * @param min the minute part of the time. Must be in the range 0-59. */ public void setTime(int hrs, int min) { // EXERCISE: We really ought to check that hrs and min are in the // right range, like we do for setHours below. // EXERCISE 2: hrs and min aren't good variable names. // Can you re-write this method to use hours and minutes // for both the parameters and the instance variables? hours = hrs; minutes = min; } /** * Set the hours * @param hours the hour part of the time. Must be in the range 1-12. */ public void setHours(int hours) { // parameter: hrs // IN-CLASS: Draw all of memory at this line of the program. if(hours <= 12 && hours> 0) { this.hours = hours; } else { System.err.println("Warning: Ignoring invalid time: "+hours); } } /** * Format the time as a string. For example, * if it is 11:15, return the string "11:15" */ public String toString() { DecimalFormat formatter = new DecimalFormat("00"); String formattedTime = hours+":"+formatter.format(minutes); return formattedTime; } /** * Simulate one tick of the clock: Print time, wait 1 second (to simulate 1 minute) * and count one minute forward. */ public void tick() { // Print current time System.out.println("Time: "+this.toString()); // Wait 1 second SleepHelper.sleep(SLEEP_TIME_MILLISECONDS); // count forward this.countMinuteForward(); } /** * Count one minute forward. * If the minute hand reaches top of the hour, * wrap around to 0 and count forward one hour * e.g. 11:58, 11:59, 12:00. */ private void countMinuteForward() { minutes+=1; if(minutes >= MINUTES_TOP_OF_CLOCK) { minutes=0; hours+=1; // EXERCISE: Make sure hours count over correctly, too. } } }