Add the following method to the TimeSpan class:
public void subtract(TimeSpan span)
Subtracts the given amount of time from this time span.
//package classes;
public class TimeSpan {
private int hours;
private int minutes;
// Construtor to pass hours and minutes
public TimeSpan(int hours, int minutes) {
this.hours = 0;
this.minutes = 0;
add(hours, minutes);
}
// this methods thorws an error if invalid hours and miutes passes into the
// argument
public void add(int hours, int minutes) {
if (hours < 0 || minutes < 0) {
throw new IllegalArgumentException();
}
this.hours += hours;
this.minutes += minutes;
// converts each 60 minutes into one hour
this.hours += this.minutes / 60;
this.minutes = this.minutes % 60;
}
public void substract(TimeSpan span) {
if (span.hours < 0 || span.minutes < 0) {
throw new IllegalArgumentException();
}
this.minutes = ((this.hours*60+this.minutes)-((span.hours*60)+span.minutes))%60;
this.hours -= span.hours;
if (this.hours < 0 || this.minutes < 0) {
throw new IllegalArgumentException();
}
}
// returns a String for this time span, such as "6h 15m"
public String toString() {
return hours + "h " + minutes + "m";
}
public static void main(String[] args) {
TimeSpan elapsed = new TimeSpan(5, 56);
TimeSpan elapsed2 = new TimeSpan(2, 56);
System.out.println("elapsed time before subtracting: " + elapsed);
System.out.println("subtract: " + elapsed2);
elapsed.substract(elapsed2);
System.out.println("elapsed time after subtracting: " + elapsed);
}
}
Output:
elapsed time before subtracting: 5h 56m
subtract: 2h 56m
elapsed time after subtracting: 3h 0m