Design a class named Time. The class contains: Data fields hour, minute and seco
ID: 3628282 • Letter: D
Question
Design a class named Time. The class contains:Data fields hour, minute and second that repsent a time.
A no-arg constructor that creates a Time object for the current time. (The values of the data fields will represent the current time)
A constructor that constructs a Time object with a specified elapsed time since midnight, Jan 1, 1970, in milliseconds. (The values of the data fields represent this time.)
A constructor that constructs a Time object with the specified hour, minute, second.
Three get methods for the data fields hour, minute, second, respectively.
A method named setTime(long elapsedTime) that sets a new time for the object using the elapsed time.
(Hint: The first two constructors will extract hour , minute, and second from the elapsed time. For example, if the elapsed time is 555550 seconds, the hour is 10, the minute is 19 and the second is 9. For the no-arg constructor, the current time can be obtained using System.currentTimeMills())
Explanation / Answer
Try the class below for starters. class Time { private long hours; private long minutes; private long seconds; public Time() { setTimeMilliseconds(System.currentTimeMillis()); } public Time(long h, long m, long s) { hours = h; minutes = m; seconds = s; } public Time(long elapsedTime) { setTimeMilliseconds(elapsedTime); } public void setTimeMilliseconds(long mTime) { mTime /= 1000; // convert to seconds // determine how many days since epoch long days = mTime / (24*60*60); mTime = mTime % (24*60*60); // determine how many hours for time hours = mTime / (60*60); mTime = mTime % (60*60); // determine how many minutes minutes = mTime / 60; // determine how many seconds seconds = mTime % 60; } public void setTime(long elapsedTime) { elapsedTime /= 1000; // convert to seconds hours += elapsedTime / (60 * 60); elapsedTime = elapsedTime % (60*60); minutes += elapsedTime / (60); elapsedTime = elapsedTime % (60); seconds += elapsedTime; } public long getHour() { return hours; } public long getMinutes() { return minutes; } public long getSeconds() { return seconds; } public void print() { System.out.println(hours + ":" + minutes + ":" + seconds); } };
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.