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);
        currentTime--;
        
         //Milliseconds get changed into seconds
        while (System.currentTimeMillis() - startTime < 1000){
           startTime -= 1;
           i--;

        System.out.println(currentTime + " remaining seconds ");
            if (i <= 0)
                break;
        }
        seconds = 0;
        System.out.println("Countdown stopped ");
     }
    }
   }

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.