StefanTobler

TERM 2 ASSIGNMENT 4

Feb 23rd, 2017
611
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | None | 0 0
  1. /*
  2.  * AP CS MOOC
  3.  * Term 2 - Assignment 4: Time Comparable
  4.  * You can use this solution to Assignment 1 in order to create a
  5. comparable time object.
  6.  * You will need to change the class so that it implements the
  7. comparable interface.
  8.  */
  9.  
  10. public class Time implements Comparable
  11. {
  12.      private int hour;
  13.      private int minute;
  14.  
  15.     /*
  16.      * Sets the default time to 12:00.
  17.      */
  18.     public Time ()
  19.     {
  20.          this(0, 0);
  21.     }
  22.  
  23.     /*
  24.      * Sets hour to h and minute to m.
  25.      */
  26.     public Time (int h, int m)
  27.     {
  28.          hour = 0;
  29.          minute = 0;
  30.          if (h >=1 && h <= 23)
  31.               hour = h;
  32.          if (m >= 1 && m <= 59)
  33.               minute = m;
  34.  
  35.     }
  36.  
  37.     /*
  38.      * Returns the time as a String of length 4 in the format: 0819.
  39.      */
  40.      public String toString ()
  41.      {
  42.  
  43.           String h = "";
  44.           String m = "";
  45.           if ( hour <10)
  46.                h +="0";
  47.           if (minute <10)
  48.                m +="0";
  49.           h += hour;
  50.           m+=minute;
  51.  
  52.           return "" + h + "" + m;
  53.      }
  54.  
  55.      public int compareTo(Object d)
  56.      {
  57.       Time temp = (Time) d;
  58.       int x = 0;
  59.       if(hour == temp.hour && minute == temp.minute)
  60.       {
  61.         x = 0;
  62.       }
  63.       else if(hour < temp.hour || (hour == temp.hour && minute < temp.minute))
  64.       {
  65.         x = -1;
  66.       }
  67.       else if(hour > temp.hour || (hour == temp.hour && minute > temp.minute))
  68.       {
  69.         x = 1;
  70.       }
  71.       return x;
  72.       }
  73.  
  74.      public String difference(Time t)
  75.      {
  76.        int min1 = (hour * 60) + minute;
  77.        int min2 = (t.hour * 60) + t.minute;
  78.        int diffmin= Math.abs(min1 - min2);
  79.  
  80.        int diffh = diffmin/60;
  81.        diffmin = diffmin%60;
  82.  
  83.  
  84.        String h = "";
  85.        String m = "";
  86.        if ( diffh <10)
  87.          h +="0";
  88.        if (diffmin <10)
  89.          m +="0";
  90.        h += diffh;
  91.        m+=diffmin;
  92.  
  93.        return "Time difference: " + h + ":" + m;
  94.  
  95.  
  96.      }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment