Clock
This single part question is worth 7 points.
AP CSA Alignment
| Unit Alignment |
Learning Objectives |
Skills |
| Unit 3: Class Creation |
3.3.A Develop code to designate access and visibility constraints to classes, data, constructors, and methods. |
2.B Write program code involving data abstractions. |
| Unit 3: Class Creation |
3.4.A Develop code to declare instance variables for the attributes to be initialized in the body of the constructors of a class. |
2.B Write program code involving data abstractions. |
| Unit 3: Class Creation |
3.5.A Develop code to define behaviors of an object through methods written in a class using primitive values and determine the result of calling these methods. |
2.C Write program code involving procedural abstraction. |
| Unit 2: Selection and Iteration |
2.9.A Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms. |
2.A Write program code to implement an algorithm. |
Directions
The Clock class, which you will write, represents a clock that stores the current time in hours and minutes using 24-hour time, for example 13:30 for 1:30pm. Clock objects are created by calls to a constructor with two parameters.
- The first parameter is an
int that represents the initial hour of the clock (0 to 23).
- The second parameter is an
int that represents the initial minutes of the clock (0 to 59).
The Clock class contains a advance method, which will modify the current time by adding the value of the int parameter, representing the number of minutes, to the current time, correctly handling minute overflow. For example, advancing 15 minutes from 13:50 results in 14:05. If advancing causes the hours to go past 23, it should wrap around to 0.
The Clock class contains a getTime method, which returns the current time as a string in the format "HH:MM", with leading zeros if needed. For example, 4:07am would be 04:07.
| Statement |
Return Value (blank if no value) |
Explanation |
String currentTime; |
|
Clock myClock = new Clock(9, 0); |
|
Clock myClock is constructed with the initial time of 09:00. |
myClock.advance(15); |
|
The current time is 09:15. |
currentTime = myClock.getTime(); |
09:15 |
The value of currentTime is 09:15. |
myClock.advance(45); |
|
The current time is 10:00. |
myClock.advance(195); |
|
The current time is 13:15. |
currentTime = myClock.getTime(); |
13:15 |
The value of currentTime is 13:15. |
Clock myClock2 = new Clock(23, 30); |
|
A second Clock object named myClock2 is created with an initial time of 23:20. |
myClock2.advance(50); |
|
The current time is 00:20. |
Write Your Response
- In order to test your program, we have provided some test cases for calls to
advance and getTime.
- Write the code for the class
Clock in the Java Playground above the provided test cases.
- All seven test should return
true if your code is correct.