Source of Time1.java


  1: // Fig. 8.1: Time1.java
  2: // Time1 class declaration maintains the time in 24-hour format.
  3: package com.deitel.jhtp6.ch08;
  4: 
  5: public class Time1  
  6: {
  7:    private int hour;   // 0 - 23
  8:    private int minute; // 0 - 59
  9:    private int second; // 0 - 59
 10: 
 11:    // set a new time value using universal time; ensure that 
 12:    // the data remains consistent by setting invalid values to zero
 13:    public void setTime( int h, int m, int s )
 14:    {
 15:       hour = ( ( h >= 0 && h < 24 ) ? h : 0 );   // validate hour
 16:       minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute
 17:       second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second
 18:    } // end method setTime
 19: 
 20:    // convert to String in universal-time format (HH:MM:SS)
 21:    public String toUniversalString()
 22:    {
 23:       return String.format( "%02d:%02d:%02d", hour, minute, second );
 24:    } // end method toUniversalString
 25: 
 26:    // convert to String in standard-time format (H:MM:SS AM or PM)
 27:    public String toString()
 28:    {
 29:       return String.format( "%d:%02d:%02d %s", 
 30:          ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
 31:          minute, second, ( hour < 12 ? "AM" : "PM" ) );
 32:    } // end method toString
 33: } // end class Time1
 34: 
 35: /**************************************************************************
 36:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 37:  * Pearson Education, Inc. All Rights Reserved.                           *
 38:  *                                                                        *
 39:  * DISCLAIMER: The authors and publisher of this book have used their     *
 40:  * best efforts in preparing the book. These efforts include the          *
 41:  * development, research, and testing of the theories and programs        *
 42:  * to determine their effectiveness. The authors and publisher make       *
 43:  * no warranty of any kind, expressed or implied, with regard to these    *
 44:  * programs or to the documentation contained in these books. The authors *
 45:  * and publisher shall not be liable in any event for incidental or       *
 46:  * consequential damages in connection with, or arising out of, the       *
 47:  * furnishing, performance, or use of these programs.                     *
 48:  *************************************************************************/