Timer

23rd October 2018

This is the Java code for a basic timer. The "timer" mode asks you to pick minute and second values and counts down from there. The "stopwatch" mode just counts up. There's no lap function on the stopwatch because it'll make more sense doing that when GUI is added.

import java.util.Scanner;

public class ProTimer {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

        while(true) {
            System.out.println("Press 1 for timer, 2 for stopwatch");
            String decision = sc.next();
            if(decision.equals("1")) {
                Timer();
                break;
            } else if(decision.equals("2")) {
                Stopwatch();
                break;
            }
        }
    }

    public static void Timer() {


        System.out.print("How many minutes? ");
        int minutes = sc.nextInt();
        System.out.print("How many seconds? ");
        int seconds = sc.nextInt();


        while(true) {
            try {
                System.out.println("Minutes: " + minutes + " " + "Seconds: " + seconds);
                Thread.sleep(1000);
                seconds--;
            } catch (InterruptedException e) {


            }


            if(seconds == -1 ) {
                seconds = 59;
                minutes--;
                if(minutes == -1) {
                    minutes = 0;
                }
            }


            if(seconds == 0 && minutes == 0) {
                System.out.println("Minutes: " + minutes + " " + "Seconds: " + seconds);
                System.out.println("DONE");
                break;
            }
        }
    }


    public static void Stopwatch() {


        while(true) {
            System.out.println("Press 's' to begin");
            String start = sc.next();
            if(start.equals("s")) {
                break;
            }
        }


        int seconds = 0;
        int minutes = 0;


        while(true) {
            try {
                System.out.println("Minutes: " + minutes + " " + "Seconds: " + seconds);
                Thread.sleep(1000);
                seconds++;
            } catch (InterruptedException e) {
            }


            if(seconds == 60 ) {
                seconds = 0;
                minutes++;
            }
        }
    }
}