Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Design a class named StopWatch. The class contains: - Private data fields startT

ID: 3670484 • Letter: D

Question

Design a class named StopWatch.

The class contains:

- Private data fields 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 cur- rent 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.

- The System.currentTimeMillis() method returns the current number of milliseconds. (Refer to Section 2.12 for further details.)

Explanation / Answer

StopWatch.java

public class StopWatch {
   private long startTime;
   private long endTime;
  
   // No-arg, initializes startTime
   StopWatch() {
       startTime = System.currentTimeMillis();
   }
  
   void start() {
       startTime = System.currentTimeMillis();
   }
  
   void stop() {
       endTime = System.currentTimeMillis();
   }
  
   long getElapsedTime() {
       return endTime - startTime;
   }
}

Main.java
import java.util.Random;

public class Main {
   public static void main(String[] args) {
      
       int[] list = new int[100000];
       Random random = new Random();
      
       // Fill list with random 100,000 integers
       for(int i = 0; i < list.length; i++) {
           list[i] = random.nextInt(100);
       }
      
       // Start timer and sort
       StopWatch stopwatch = new StopWatch();
       selectionSort(list);
      
       stopwatch.stop();
       System.out.println((stopwatch.getElapsedTime() / 1000) + "s");
   }
  
   public static void selectionSort(int[] x) {
       for(int i = 0; i < x.length; i++) {
           int minIndex = i;
           for(int j = i + 1; j < x.length; j++) {
               if(x[minIndex] > x[j]) {
                   minIndex = j;
               }
           }
           if(minIndex != i) {
               int temp = x[i];
               x[i] = x[minIndex];
               x[minIndex] = temp;
           }
       }
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote