Java Programming Task 1 With Solution

Java programming task 1


Task 1 :


Design a class named StopWatch. The class contains:
  • 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.
Write a test program and create a stopwatch and call all methods.

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

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);
}
}
view raw Task-1.java hosted with ❤ by GitHub
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
}
}
view raw Test.java hosted with ❤ by GitHub

Comments

Popular posts from this blog

Pseudocode to Check, Number is Odd or Even

How to Create Marksheet in C

C Program to Calculate Acceleration