Problem of the Day
Thursday, May 16, 2024
Problem:
The TimeKeeper
class models a clock or watch that keeps track of the passage of time in a 24-hour cycle:
- at midnight it is
0
hours,0
minutes, and0
seconds - at noon it is
12
hours - one second before midnight it is
23
hours,59
minutes, and59
seconds
The tick
method is called once a second, updating the instance variables appropriately. A partial implementation of the class is given here.
public class TimeKeeper
{
private int hours;
private int minutes;
private int seconds;
public TimeKeeper(int hours, int minutes, int seconds)
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
/**
* Adds one second to the clock and adjusts all three instance variables accordingly
*/
public void tick()
{
/* missing code */
}
/* other methods not shown */
}
Which of the following could be used to replace /* missing code */
so that the tick
method will work as intended?
seconds += 1;
if (seconds / 60 == 1)
{
minutes += 1;
seconds = seconds % 60;
}
if (minutes / 60 == 1)
{
hours += 1;
minutes = minutes % 60;
}
hours = hours % 24;seconds += 1;
if (seconds / 60 == 1)
{
minutes += 1;
seconds = seconds / 60;
}
if (minutes / 60 == 1)
{
hours += 1;
minutes = minutes / 60;
}
hours = hours % 24;seconds += 1;
if (seconds % 60 == 1)
{
minutes += 1;
seconds = seconds % 60;
}
if (minutes % 60 == 1)
{
hours += 1;
minutes = minutes % 60;
}
hours = hours % 24;seconds += 1;
if (seconds / 60 == 1)
{
minutes += 1;
seconds = seconds % 60;
}
if (minutes / 60 == 1)
{
hours += 1;
minutes = minutes % 60;
}
hours = hours / 24;seconds += 1;
if (seconds / 60 == 1)
{
minutes += 1;
seconds = seconds % 60;
}
if (minutes / 60 == 1)
{
hours += 1;
minutes = minutes % 60;
}
hours = 24 - hours;
The correct answer is a. The seconds
will increase by 1, with adjustments to the seconds
if 59 seconds have passed. Also, adjustments will be made to minutes
(if more than 59 minutes have passed) and hours
(if more than 24 hours have passed.