Define a class named TimeSpan. A TimeSpan object stores a span of time in hours and minutes (for example, the time span between 5:00am and 7:45am is 2 hours, 45 minutes). Each TimeSpan object should have the following public methods:
TimeSpan(hours, minutes)
Constructs a TimeSpan object storing the given time span of hours and minutes.
getHours()
Returns the number of hours in this time span.
getMinutes()
Returns the number of minutes in this time span, between 0 and 59.
add(hours, minutes)
Adds the given amount of time to the span. For example, (3 hours, 15 minutes) + (2 hour, 40 minutes) = (5 hours, 55 minutes). Assume that the parameters are valid: the hours are non-negative, and the minutes are between 0 and 59.
add(TimeSpan tp)
Adds the given amount of time (stored as a time span) to the current time span.
getTotalHours()
Returns the total time in this time span as the real number of hours, such as 9.75 for (9 hours, 45 min).
toString()
Returns a string representation of the time span of hours and minutes, such as "5 Hours, 38 Minutes".
The minutes should always be reported as being in the range of 0 to 59. That means that you may have to "carry" 60 minutes into a full hour.
class TimeSpan {
private int hours;
private int minutes;
// Constructor to initialize TimeSpan object with given hours and minutes
public TimeSpan(int hours, int minutes) {
this.hours = hours;
this.minutes = minutes;
normalizeTime(); // Ensure minutes are within 0-59
}
// Method to get the number of hours
public int getHours() {
return hours;
}
// Method to get the number of minutes
public int getMinutes() {
return minutes;
}
// Method to add given hours and minutes to the current TimeSpan
public void add(int hours, int minutes) {
this.hours += hours;
this.minutes += minutes;
normalizeTime();
}
// Method to add another TimeSpan to the current TimeSpan
public void add(TimeSpan tp) {
this.hours += tp.hours;
this.minutes += tp.minutes;
normalizeTime();
}
// Method to get total time as real number hours (e.g. 9.75 for 9 hours, 45 minutes)
public double getTotalHours() {
return hours + minutes / 60.0;
}
// Method to return a string representation of the time span
public String toString() {
return hours + " Hours, " + minutes + " Minutes";
}
// Private method to normalize time (convert minutes > 59 into hours)
private void normalizeTime() {
if (minutes >= 60) {
hours += minutes / 60;
minutes = minutes % 60;
}
}
}