// Times.java (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // 2004-10-07 File created. // 2005-03-02 Last modification. 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 Times { 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 Any other number gives the 24-hour format. " ) ; int user_response = keyboard.nextInt() ; if ( user_response == 12 ) { time_to_show = new AmericanTime() ; } else { time_to_show = new EuropeanTime() ; } System.out.print( "\n The time is now " ) ; time_to_show.print() ; System.out.print( "\n" ) ; } }