Learn AP Comp Sci

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:

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?


  1. seconds += 1;
    if (seconds / 60 == 1)
    {
    minutes += 1;
    seconds = seconds % 60;
    }
    if (minutes / 60 == 1)
    {
    hours += 1;
    minutes = minutes % 60;
    }
    hours = hours % 24;

  2. seconds += 1;
    if (seconds / 60 == 1)
    {
    minutes += 1;
    seconds = seconds / 60;
    }
    if (minutes / 60 == 1)
    {
    hours += 1;
    minutes = minutes / 60;
    }
    hours = hours % 24;

  3. seconds += 1;
    if (seconds % 60 == 1)
    {
    minutes += 1;
    seconds = seconds % 60;
    }
    if (minutes % 60 == 1)
    {
    hours += 1;
    minutes = minutes % 60;
    }
    hours = hours % 24;

  4. seconds += 1;
    if (seconds / 60 == 1)
    {
    minutes += 1;
    seconds = seconds % 60;
    }
    if (minutes / 60 == 1)
    {
    hours += 1;
    minutes = minutes % 60;
    }
    hours = hours / 24;

  5. seconds += 1;
    if (seconds / 60 == 1)
    {
    minutes += 1;
    seconds = seconds % 60;
    }
    if (minutes / 60 == 1)
    {
    hours += 1;
    minutes = minutes % 60;
    }
    hours = 24 - hours;

Show solution:

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.