Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * AP CS MOOC
- * Term 2 - Assignment 4: Time Comparable
- * You can use this solution to Assignment 1 in order to create a
- comparable time object.
- * You will need to change the class so that it implements the
- comparable interface.
- */
- public class Time implements Comparable
- {
- private int hour;
- private int minute;
- /*
- * Sets the default time to 12:00.
- */
- public Time ()
- {
- this(0, 0);
- }
- /*
- * Sets hour to h and minute to m.
- */
- public Time (int h, int m)
- {
- hour = 0;
- minute = 0;
- if (h >=1 && h <= 23)
- hour = h;
- if (m >= 1 && m <= 59)
- minute = m;
- }
- /*
- * Returns the time as a String of length 4 in the format: 0819.
- */
- public String toString ()
- {
- String h = "";
- String m = "";
- if ( hour <10)
- h +="0";
- if (minute <10)
- m +="0";
- h += hour;
- m+=minute;
- return "" + h + "" + m;
- }
- public int compareTo(Object d)
- {
- Time temp = (Time) d;
- int x = 0;
- if(hour == temp.hour && minute == temp.minute)
- {
- x = 0;
- }
- else if(hour < temp.hour || (hour == temp.hour && minute < temp.minute))
- {
- x = -1;
- }
- else if(hour > temp.hour || (hour == temp.hour && minute > temp.minute))
- {
- x = 1;
- }
- return x;
- }
- public String difference(Time t)
- {
- int min1 = (hour * 60) + minute;
- int min2 = (t.hour * 60) + t.minute;
- int diffmin= Math.abs(min1 - min2);
- int diffh = diffmin/60;
- diffmin = diffmin%60;
- String h = "";
- String m = "";
- if ( diffh <10)
- h +="0";
- if (diffmin <10)
- m +="0";
- h += diffh;
- m+=diffmin;
- return "Time difference: " + h + ":" + m;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment