1. Create a class named Clock. You should use your IDE for this exercise. The cl
ID: 664793 • Letter: 1
Question
1. Create 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.
2. 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.time classes.
Here is sample run:
java TestClock 11:45:12 11:48:13
Elapsed time in seconds is: 181
Explanation / Answer
ANSWER:
1.Clock.java
//HEADER FILES
import java.time.LocalTime;
import java.lang.*;
// CREATING CLASS CLOCK
public class Clock
{
// PRIVATE DATA FIELDS
private LocalTime a_startTime1;
private LocalTime a_stopTime1;
// NO ARGUMENT COSNTRUCTOR TO INITILIZE STARTTIME TO CURRENT TIME
protected Clock()
{
a_startTime1 = LocalTime.now();
}
//METHOD start() RESETS THE startTime TO THE GIVEN TIME
protected void start(LocalTime time1)
{
a_startTime1 = time1
}
//METHOD stop() SETS THE endtime TO GIVEN TIME
protected void stop(LocalTime time2)
{
a_stopTime1 = time2;
}
//getElapsedTime() METHOD RETURNS ELAPSED TIME IN SECONDS
private int getElapsedTime()
{
int a_elapsedTime1 = a_stopTime1.getSecond() - a_startTime1.getSecond();
return a_elapsedTime1;
}
public String toString()
{
String sstr1;
sstr1= “ELAPSED TIME IS SECONDS: " + getElapsedTime();
return sstr1;
}
}
2.TestClock.java
// HEADER FILES
import java.time.LocalTime;
import java.lang.*;
// CREATING CLASS TestClock
class TestClock
{
// CONSTRUCT A CLOCK INSTANCE AND RETURN ELAPSED TIME
public static void main(String[] args)
{
// CREATING OBJECT
Clock a_newClock1 = new Clock();
// CHECKING THE CONDITION USING LOOP
if (args.length == 2)
{
LocalTime a_startTime1 = LocalTime.parse(args[0]);
LocalTime a_endTime1 = LocalTime.parse(args[1]);
}
else {
err.println("ARGUMENTS ERROR");
System.exit(1);
}
a_newClock1.start(a_startTime1);
a_newClock1.start(a_endTime1);
// DISPLAY NEW CLOCK VALUE
System.out.println(a_newClock1);
} //end main
} //end TestClock
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.