Answer:
Check the explanation
Explanation:
Here is the modified code for
TimeSpan.java and TimeSpanClient.java.
// TimeSpan.java
//implemented Comparable interface, which has the compareTo method
//and can be used to sort a list or array of TimeSpan objects without
//using a Comparator
public class TimeSpan implements Comparable<TimeSpan> {
private int totalMinutes;
// Constructs a time span with the given interval.
// pre: hours >= 0 && minutes >= 0
public TimeSpan(int hours, int minutes) {
totalMinutes = 0;
add(hours, minutes);
}
// Adds the given interval to this time span.
// pre: hours >= 0 && minutes >= 0
public void add(int hours, int minutes) {
totalMinutes += 60 * hours + minutes;
}
// Returns a String for this time span such as "6h15m".
public String toString() {
return (totalMinutes / 60) + "h" + (totalMinutes % 60) + "m";
}
// method to compare this time span with other
// returns a negative value if this time span is shorter than other
// returns 0 if both have same duration
// returns a positive value if this time span is longer than other
public int compareTo(TimeSpan other) {
if (this.totalMinutes < other.totalMinutes) {
return -1; // this < other
} else if (this.totalMinutes > other.totalMinutes) {
return 1; // this > other
} else {
return 0; // this = other
}
}
}
// TimeSpanClient.java
public class TimeSpanClient {
public static void main(String[] args) {
int h1 = 13, m1 = 30;
TimeSpan t1 = new TimeSpan(h1, m1);
System.out.println("New object t1: " + t1);
h1 = 3;
m1 = 40;
System.out.println("Adding " + h1 + " hours, " + m1 + " minutes to t1");
t1.add(h1, m1);
System.out.println("New t1 state: " + t1);
// creating another TimeSpan object, testing compareTo method using the
// two objects
TimeSpan t2 = new TimeSpan(10, 20);
System.out.println("New object t2: " + t2);
System.out.println("t1.compareTo(t2): " + t1.compareTo(t2));
System.out.println("t2.compareTo(t1): " + t2.compareTo(t1));
System.out.println("t1.compareTo(t1): " + t1.compareTo(t1));
}
}
/*OUTPUT*/
New object t1: 13h30m
Adding 3 hours, 40 minutes to t1
New t1 state: 17h10m
New object t2: 10h20m
t1.compareTo(t2): 1
t2.compareTo(t1): -1
t1.compareTo(t1): 0