Problem of the Day
Problem:
Consider the following class which is intended to model a clock or watch that keeps track of the current time on a 24-hour clock.
public class TimeKeeper
{
private int hours;
private int minutes;
private int seconds;
/* Constructor and methods not shown */
}
A method tick()
is called every second, and the values of the three instance variables are updated appropriately.
The time of 6 hours, 3 minutes, and 59 seconds, for example, after the tick()
method is called, would have values changed to 6 hours, 4 minutes, and 0 seconds. Likewise, 23 hours, 59 minutes, and 59 seconds, after the tick()
method is called, would have values changed to 0 hours, 0 minutes, and 0 seconds.
Which of the following should replace /* missing code */
so that the method will work as intended?
public void tick()
{
seconds += 1;
/* missing code */
}
if (seconds / 60 == 1)
minutes += 1;
}
if (minutes / 60 == 1)
{
hours += 1;
}
hours = hours % 24;if (seconds / 60 == 1)
minutes += 1;
}
if (minutes / 60 == 1)
{
hours += 1;
}if (seconds % 60 == 1)
{
minutes += 1;
seconds = seconds / 60;
}
if (minutes % 60 == 1)
{
hours += 1;
minutes = minutes / 60;
}
hours = hours / 24;if (seconds / 60 == 1)
{
minutes += 1;
seconds = seconds % 60;
}
if (minutes / 60 == 1)
{
hours += 1;
minutes = minutes % 60;
}
hours = hours % 24;
The correct answer is d. Once the seconds
have been updated, the unit value of minutes
and hours
have to be updated as well, but only if the smaller time has incremented such that it "ticks over," resulting in an increase in the next larger unit.