// TimesWithTextualTime.cs (c) 2004 Kari Laitinen // http://www.naturalprogramming.com // 2005-03-02 File created. // 2004-03-02 Last modification. // A solution to Exercise 12-9 import java.util.* ; abstract class CurrentTime { protected int current_hours ; protected int current_minutes ; protected int current_seconds ; public CurrentTime() { Calendar current_system_time = new GregorianCalendar() ; current_hours = current_system_time.get( Calendar.HOUR_OF_DAY ) ; current_minutes = current_system_time.get( Calendar.MINUTE ) ; current_seconds = current_system_time.get( Calendar.SECOND ) ; } abstract public void print() ; } // It is not entirely true that the 12-hour a.m./p.m. time // would be used everywhere in America, and the 24-hour time // would be used everywhere in Europe. The names AmericanTime // and EuropeanTime just happen to be nice names to // distinguish these two different ways to display time. class AmericanTime extends CurrentTime { public void print() { int[] american_hours = { 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } ; System.out.printf( "%d:%02d:%02d", american_hours[ current_hours ], current_minutes, current_seconds ) ; if ( current_hours < 12 ) { System.out.print( " a.m." ) ; } else { System.out.print( " p.m." ) ; } } } class EuropeanTime extends CurrentTime { public void print() { System.out.printf( "%d:%02d:%02d", current_hours, current_minutes, current_seconds ) ; } } class TextualTime extends CurrentTime { public void print() { String[] textual_hours = { "midnight", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "noon", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven" } ; System.out.printf( "%02d minutes and %02d seconds past %s", current_minutes, current_seconds, textual_hours[ current_hours ] ) ; if ( current_hours < 6 ) { System.out.print( " at night" ) ; } else if ( current_hours < 12 ) { System.out.print( " in the morning" ) ; } else if ( current_hours < 18 ) { System.out.print( " in the afternoon" ) ; } else { System.out.print( " in the evening" ) ; } } } class TimesWithTextualTime { public static void main( String[] not_in_use ) { Scanner keyboard = new Scanner( System.in ) ; CurrentTime time_to_show ; System.out.print( "\n Type 12 to see the time in 12-hour a.m./p.m format." + "\n Type 24 to see the time in 24-hour format." + "\n Any other number gives a textual time format. " ) ; int user_response = keyboard.nextInt( ) ; if ( user_response == 12 ) { time_to_show = new AmericanTime() ; } else if ( user_response == 24 ) { time_to_show = new EuropeanTime() ; } else { time_to_show = new TextualTime() ; } System.out.print( "\n The time is now " ) ; time_to_show.print() ; System.out.print( "\n" ) ; } }