Create Simple Stopwatch in Java

What is StopWatch in java?

Create a stopwatch using Java programming. We’llĀ  build a basic stopwatch that starts, stops, and resets, allowing you to track time conveniently. This stopwatch provides a seamless experience, enabling you to initiate time measurement as needed and halt it with a simple stop command.

What is approach to implement StopWatch ?

  • Handle user commands using Scanner.
    • Start
    • Stop
    • Exit
  • Capture start time.
  • Calculate elapsed time.
  • Ensure clear prompts for user interaction.
  • Display the time to console

Program: Implement Stopwatch in java

import java.util.Scanner;
public class SimpleStopwatch {
    private long startTime;
    private boolean isRunning;

    public void start() {
        if (!isRunning) {
            startTime = System.currentTimeMillis();
            isRunning = true;
            System.out.println("Stopwatch started.");
        } else {
            System.out.println("Stopwatch is already running.");
        }
    }

    public void stop() {
        if (isRunning) {
            long endTime = System.currentTimeMillis();
            long elapsedTime = endTime - startTime;
            isRunning = false;
            System.out.println("Stopwatch stopped. Elapsed time: " + formatTime(elapsedTime));
        } else {
            System.out.println("Stopwatch is not running.");
        }
    }

    private String formatTime(long milliseconds) {
        long seconds = milliseconds / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;

        seconds %= 60;
        minutes %= 60;

        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        SimpleStopwatch stopwatch = new SimpleStopwatch();

        boolean isAppRunning = true;
        while (isAppRunning) {
            System.out.println("Enter 'start' to begin, 'stop' to end, or 'exit' to stop the application:");
            String input = scanner.nextLine();

            switch (input.toLowerCase()) {
                case "start":
                    stopwatch.start();
                    break;
                case "stop":
                    stopwatch.stop();
                    break;
                case "exit":
                    isAppRunning = false;
                    break;
                default:
                    System.out.println("Invalid input. Please enter 'start', 'stop', or 'exit'.");
                    break;
            }
        }

        scanner.close();
    }
}

Output: Simple stopwatch in java

Enter 'start' to begin, 'stop' to end, or 'exit' to stop the application:
start
Stopwatch started.
Enter 'start' to begin, 'stop' to end, or 'exit' to stop the application:
stop
Stopwatch stopped. Elapsed time: 00:00:50
Scroll to Top