Java Simple Stopwatch Project
Java Project - Measure Time Using Millis or Nano:
Simple Stopwatch:
Input: Start and stop commands.
Output: Elapsed time when the stopwatch is stopped.
Example:
- Input: "Start stopwatch"
- Output: "Stopwatch started."
- After some time: "Stop stopwatch"
- Output: "Elapsed time: 12.34 seconds."
Solution 1: Simple Stopwatch using System.currentTimeMillis()
Code:
Output:
Enter 'start' to begin the stopwatch: start Stopwatch started.
Enter 'stop' to stop the stopwatch: stop Elapsed time: 8.425 seconds.
Explanation :
- Uses System.currentTimeMillis() to record time in milliseconds.
- Starts and stops the stopwatch using user input.
- Calculates and prints the elapsed time in seconds.
Solution 2: Simple Stopwatch using nanoTime()
Code:
Output:
Enter 'start' to begin the stopwatch: start Stopwatch started.
Enter 'stop' to stop the stopwatch: stop Elapsed time: 16.259088781 seconds.
Explanation:
- Uses System.nanoTime() for higher precision timing in nanoseconds.
- Same user input logic as the first solution, but with greater accuracy.
- Outputs the time in seconds after converting nanoseconds.
Java Code Editor: