I've toyed around a great deal trying to get my calculations correct in this countdown program, but I keep getting the same result. Basically, I'm creating a program that will countdown from a users inputted number. At each second it will display whatever amount of seconds remaining. My problem is when I run the program it spits out the numbers quickly and doesn't pause for a second. I know I could very well pause it with thread.sleep, but I am trying to do it the long way, so to speak. If you guys could shoot me back in the right direction, I'd greatly appreciate it.

import java.util.Scanner;

public class StevensCountdown {
    public static void main(String[] args) {

        //Get the number of seconds from the user's input
        Scanner userInput = new Scanner(System.in);
        System.out.println("Enter the number of seconds:");
        int seconds = userInput.nextInt();
        //Get the starting time
        long startTime = System.currentTimeMillis();
        //Subtract seconds from user input
        for(int i = seconds; i > 0; i--){
        long currentTime = (int)(startTime % 60);
         //Milliseconds get changed into seconds
        while (System.currentTimeMillis() - startTime < 1000){
           startTime -= 1;

        System.out.println(currentTime + " remaining seconds ");
            if (i <= 0)
        seconds = 0;
        System.out.println("Countdown stopped ");
6 Years
Discussion Span
Last Post by masijade

Because that check in the while loop takes much less than a single millisecond to execute, so, "subtracting a millisecond" is every iteration is, of course, faster than "realtime". Simply keep checking the currentTime against the "startTime", and set the "startTime" to the currentTime as soon as it is at least 1000. You do know that your CPU usage will jump to 100% doing this, right? This is what is called "busy looping". That is why you should be using things like sleep and wait.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.