Advertisement
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(12, 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;
- }
- public int compareTo(Object other)
- {
- Time temp = (Time) other;
- int num = 0;
- if (temp.hour<hour)
- {
- num = 1;
- }
- else if (temp.hour==hour)
- {
- if (temp.minute<minute)
- {
- num = 1;
- }
- else if (temp.minute==minute)
- {
- num = 0;
- }
- else
- {
- num = -1;
- }
- }
- else
- {
- num = -1;
- }
- return num;
- }
- public String difference(Time t)
- {
- Time temp = (Time) t;
- String h = "";
- String m = "";
- if (t.hour>hour)
- {
- /*if ((t.hour-hour)>12)
- {
- h+=(t.hour-hour)-12;
- }
- else */
- {
- h+=t.hour-hour;
- }
- }
- else if (t.hour<hour)
- {
- /*if ((hour-t.hour)>12)
- {
- h+=(hour-t.hour)-12;
- }
- else */
- {
- h+=hour-t.hour;
- }
- }
- else
- {
- h+=0;
- h+=0;
- }
- if (t.minute>minute)
- {
- m+=(t.minute-minute);
- }
- else if (minute>t.minute)
- {
- m+=(minute-t.minute);
- }
- else
- {
- m+=0;
- m+=0;
- }
- return h + ":" + 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement