Define a class named TimeSpan. A TimeSpan object stores a span of time in hours
ID: 3564627 • Letter: D
Question
Define a class named TimeSpan. A TimeSpan object stores a span of time in hours and minutes (for example, the time span between 8:00am and 10:30am is 2 hours, 30 minutes). Each TimeSpan object should have the following public methods:
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.
I got this far:
public class TimeSpan {
private int myHours;
private int myMinutes;
public TimeSpan(int hours, int minutes){
public void add(int hours, int minutes) {
this.myHours = hours;
this.myMinutes = minutes;
}
public int getHours() {
return this.myHours = hours;
}
public int getMinutes() {
return this.myMinutes = minutes;
}
public void add(TimeSpan rhs)
{
hours += rhs.hours;
minutes += rhs.minutes;
hours += minutes/60;
minutes = minutes%60;
}
}
}
I don't know what is wrong now....
Explanation / Answer
// A TimeSpan object represents a duration of time in hours and minutes.
public class TimeSpan {
private int hours;
private int minutes;
// Constructs a time span representing the given number of hours and minutes.
public TimeSpan(int initialHours, int initialMinutes) {
hours = 0;
minutes = 0;
add(initialHours, initialMinutes);
}
// Adds the given hours/minutes to this time span, wrapping hours if necessary.
public void add(int initialHours, int initialMinutes) {
hours += initialHours;
minutes += initialMinutes;
if (minutes >= 60) {
minutes -= 60; // convert 60 min --> 1 hour
hours++;
}
}
// Adds the given hours/minutes to this time span, wrapping hours if necessary.
public void add(TimeSpan span) {
add(span.hours, span.minutes);
}
// Returns the total hours represented by this time span,
// such as 7.75 for 7 hours, 45 minutes.
public double getTotalHours() {
return hours + minutes / 60.0;
}
// Returns a text representation of this time span, such as "7h45m".
public String toString() {
return hours + "h" + minutes + "m";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.