Design a class named Clock. You should use your IDE for this exercise. The class
ID: 3671642 • Letter: D
Question
Design a class named Clock. You should use your IDE for this exercise. The class contains private data fields for startTime and stopTime, a no argument constructor that initializes the startTime to the current time, a method named start() that resets the startTime to the given time, a stop()method that sets the endTime to the given time and a getElapsedTime() method that returns the elapsed time in seconds. Create a TestClock class to construct a Clock instance and return the elapsed time. Command line arguments should be used to send the start and end times. You should use the java.timeclasses Here is samplerun: java TestClock 11:45:12 11:48:13 Elapsed time in seconds is:181
Explanation / Answer
Clock.java
import java.time.LocalTime;
public class Clock {
// Private data fields
private LocalTime startTime;
private LocalTime stopTime;
// No-argument contsructor that sets startTime
public Clock() {
this.startTime = LocalTime.now();
}
// start() method that sets startTime to args[0]
public LocalTime start(LocalTime start) {
return this.startTime = start;
}
// stop() method that sets stopTime to args[1]
public LocalTime stop(LocalTime stop) {
return this.stopTime = stop;
}
// Method that calculates the seconds between args
public long getElapsedTime() {
return java.time.Duration.between(
this.startTime, this.stopTime
).getSeconds();
}
// Getters
public LocalTime getStartTime() {
return startTime;
}
public LocalTime getStopTime() {
return stopTime;
}
}
TestClock.java
import java.time.LocalTime;
public class TestClock {
public static void runClock(LocalTime startArg, LocalTime stopArg) {
// Creates a new Clock class named ticker
Clock ticker = new Clock();
// Uses the first argument to set the startTime
ticker.start(startArg);
// Uses the second argument to set the stopTime
ticker.stop(stopArg);
// Displays startTime and stopTime
System.out.println("java TestClock " +
ticker.getStartTime() + " " + ticker.getStopTime());
// Uses getElapsedTime to display the seconds between the two args
System.out.println("Elapsed time in seconds is: " +
ticker.getElapsedTime());
}
public static void main(String[] args) {
// Passes arguments to the runClock method above
runClock(LocalTime.parse(args[0]), LocalTime.parse(args[1]));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.