Java Programming Task 1 With Solution
Task 1 :
- Private data fields are startTime and endTime with getter methods.
- A no-arg constructor that initializes startTime with the current time.
- A method named start() that resets the startTime to the current time.
- A method named stop() that sets the endTime to the current time.
- A method named getElapsedTime() that returns the elapsed time for the stopwatch in milliseconds.
Solution :
The task is explanatory itself, if you focus however here's an explanation for you:
- First of all, declare two private data fields 'startTime' & 'endTime' as said in the task, as we know the time can set in seconds means values in points, therefore, we have to use data type float.
- Then, we have asked to create a no argument constructor which will be used to initialize the current time.
- Then we have to create methods of start, stop and getEplasedTime to get elapsed time.
- In the end, we have been told that create two classes one is Test class another is StopWatch class.
- In the StopWatch class, we'll do all of our work such as the declaration of variables and creation of method.
- And in the Test class, we'll call method created in StopWatch class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StopWatch | |
{ | |
// private data fields | |
private float startTime; | |
private float endTime; | |
// getter methods | |
public float getStartTime(){ | |
return startTime; | |
} | |
public float getEndTime() | |
{ | |
return endTime; | |
} | |
// no - arg constructor | |
public StopWatch() | |
{ | |
} | |
// start method | |
public void start(float startTime) | |
{ | |
this.startTime = startTime; | |
} | |
//stop method | |
public void stop(float endTime) | |
{ | |
this.endTime = endTime; | |
} | |
// elpsed time method | |
public float getElapsedTime() | |
{ | |
return ((endTime - startTime) * 1000); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Test | |
{ | |
public static void main(String[] args) | |
{ | |
StopWatch stopwatch1 = new StopWatch(); // object of stopwatch class | |
stopwatch1.start(10); // reseting the start time through method calling | |
stopwatch1.stop(20); // setting the stop time through method calling | |
stopwatch1.getStartTime(); // getting the start time through method calling | |
stopwatch1.getEndTime(); // getting the stop time through method calling | |
stopwatch1.getElapsedTime(); // getting the elapsed time through method calling | |
} | |
} |
Comments
Post a Comment