OneCompiler

Timer / stopwatch

1655

Example heading with h2 size

Example heading with h3 size

Following is sample java code.

int i = 10;
if(i>0){
    System.out.println('positive');
}
```import java.util.Timer;
import java.util.TimerTask;
import java.util.Scanner;

public class Stopwatch {
    private static long startTime;
    private static boolean running = false;
    private static Timer timer = new Timer();
    
    public static void start() {
        if (!running) {
            startTime = System.currentTimeMillis();
            running = true;
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    long elapsedTime = System.currentTimeMillis() - startTime;
                    System.out.printf("Elapsed Time: %d seconds%n", elapsedTime / 1000);
                }
            }, 0, 1000);
        }
    }

    public static void stop() {
        if (running) {
            timer.cancel();
            running = false;
            System.out.println("Stopwatch stopped.");
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String command;
        
        System.out.println("Enter 'start' to start the stopwatch, 'stop' to stop it, or 'exit' to quit:");
        
        while (true) {
            command = scanner.nextLine();
            if (command.equalsIgnoreCase("start")) {
                start();
            } else if (command.equalsIgnoreCase("stop")) {
                stop();
            } else if (command.equalsIgnoreCase("exit")) {
                stop();
                break;
            } else {
                System.out.println("Invalid command. Please enter 'start', 'stop', or 'exit'.");
            }
        }
        
        scanner.close();
    }
}