glennluc

8.5

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