Advertisement
lamaulfarid

Time2

Oct 14th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. /**
  2.  * Write a description of class Time2 here.
  3.  * Time2 class declaration with overloaded constructors.
  4.  * @author Ahmad Lamaul Farid
  5.  * @version 08 Oktober 2020
  6.  */
  7. public class Time2
  8. {
  9.     private int hour;
  10.     private int minute;
  11.     private int second;
  12.    
  13.     public Time2()
  14.     {
  15.         this( 0, 0, 0 );
  16.     }
  17.    
  18.     public Time2( int h )
  19.     {
  20.         this( h, 0, 0 );
  21.     }
  22.    
  23.     public Time2( int h, int m )
  24.     {
  25.        this( h, m, 0 );
  26.     }
  27.    
  28.     public Time2( int h, int m, int s )
  29.     {
  30.        setTime( h, m, s );
  31.     }
  32.    
  33.     public Time2( Time2 time )
  34.     {
  35.        this( time.getHour(), time.getMinute(), time.getSecond() );
  36.     }  
  37.    
  38.    
  39.     public void setTime( int h, int m, int s )
  40.     {
  41.        setHour( h );
  42.        setMinute( m );
  43.        setSecond( s );
  44.     }
  45.    
  46.     public void setHour( int h )
  47.     {
  48.        if ( h >= 0 && h < 24 )
  49.           hour = h;
  50.        else
  51.           throw new IllegalArgumentException( "hour must be 0-24" );
  52.     }
  53.  
  54.     public void setMinute( int m )
  55.     {
  56.        if ( m >= 0 && m < 60 )
  57.           minute = m;
  58.        else
  59.           throw new IllegalArgumentException( "minute must be 0-59" );
  60.     }
  61.    
  62.     public void setSecond( int s )
  63.     {
  64.        if ( s >= 0 && s < 60 )
  65.           second = ( ( s >= 0 && s < 60 ) ? s : 0 );
  66.        else
  67.           throw new IllegalArgumentException( "second must be 0-59" );
  68.     }
  69.    
  70.     public int getHour()
  71.     {
  72.        return hour;
  73.     }
  74.    
  75.    
  76.    public int getMinute()
  77.    {
  78.       return minute;
  79.    }
  80.    
  81.    public int getSecond()
  82.    {
  83.       return second;
  84.    }
  85.    
  86.    public String toUniversalString()
  87.    {
  88.       return String.format(
  89.         "%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
  90.    }
  91.    
  92.    public String toString()
  93.    {
  94.        return String.format( "%d:%02d:%02d %s",
  95.           ( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
  96.           getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
  97.     }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement