Question: Update the code public class Time { private int hour; private int minute; /* * Sets the default time to 12:00. */ public Time ()
Update the code
public class Time { 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; } /* * 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; } }
First, you will need to update Time so that it implements the Comparable interface. This will require adding an implements statement to the class declaration as well as the compareTo method. Then, you will need to add a difference method to the class. These two methods' requirements are as follows:
compareTo(Object other)
//Returns -1 if current time is less than other.
//Returns 0 if current time is equal to other.
//Returns 1 if current time is greater than other.
String difference(Time t)
//Returns a String holding the difference between the current time and
//the Time t passed in via parameter. All values should be positive,
//and in the format:
//08:09
//10:35
To test your code, download and run the code below
public static void main(String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
// time 1 Time t1 = new Time(17, 12); System.out.println(t1);
Time t2 = new Time(9, 45); System.out.println(t2); System.out.println("Greater Than:"); System.out.println(t1.compareTo(t2)); System.out.println("Less Than:"); System.out.println(t2.compareTo(t1)); System.out.println("Times equal:"); Time t3 = new Time(9, 45); System.out.println(t3.compareTo(t2)); System.out.println("Hours equal:"); Time t4 = new Time(8, 45); Time t5 = new Time(8, 34); System.out.println(t4.compareTo(t5)); System.out.println(t5.compareTo(t4)); System.out.println("Difference"); System.out.println(t4.difference(t5)); System.out.println(t5.difference(t4)); System.out.println(t4.difference(t4)); }// main
}// class
Loading. We will use a different, but similar, test class to grade the program. You will need to change the runner to test with other values to make sure your program fits all the requirements.
Sample Run of student_runner_time.java:
1712
0945
Greater than:
1
Less than:
-1
Times equal:
0
Hours equal:
1
-1
Difference
00:11
00:11
00:00
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
