srachmadbudi

PBO_8.5

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