UNIT-3-Material (1)
UNIT-3-Material (1)
@Override
public void run() {
while (running) {
try {
Thread.sleep(interval); // Wait for the
specified interval
elapsedTime += interval; // Increment the
elapsed time
displayTime();
} catch (InterruptedException e) {
System.out.println("Stopwatch
interrupted.");
}
}
}
while (true) {
System.out.print("Enter command (start,
stop, reset, exit): ");
command = scanner.next().toLowerCase();
switch (command) {
case "start":
stopwatch.start();
System.out.println("Stopwatch
started.");
break;
case "stop":
stopwatch.stop();
System.out.println("Stopwatch
stopped.");
break;
case "reset":
stopwatch.reset();
System.out.println("Stopwatch reset.");
break;
case "exit":
stopwatch.stop();
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid command.
Try again.");
}
}
}
}
Output:
Enter time interval in milliseconds for stopwatch
updates: 1000
Enter command (start, stop, reset, exit): start
Stopwatch started.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:01
Elapsed Time: 00:00:02
Elapsed Time: 00:00:03
Elapsed Time: 00:00:04
stopElapsed Time: 00:00:05
Stopwatch stopped.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:06
start
Stopwatch started.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:07
Elapsed Time: 00:00:08
Elapsed Time: 00:00:09
Elapsed Time: 00:00:10
Elapsed Time: 00:00:11
Elapsed Time: 00:00:12
Elapsed Time: 00:00:13
Elapsed Time: 00:00:14
resetElapsed Time: 00:00:15
Stopwatch reset.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:01
Elapsed Time: 00:00:02
Elapsed Time: 00:00:03
Elapsed Time: 00:00:04
Elapsed Time: 00:00:05
stopElapsed Time: 00:00:06
Stopwatch stopped.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:07