Search code examples
javafor-loopcountdown

Is it possible in Java to show the results of a for loop in only one Output?


I have a little code that displays a countdown in the console.

for(int i = this.roundTimerMinute; i > -1; i--)
    {
        for(int j = this.roundTimerSeconds; j > 0; j--)
        {

            if( j < 10)
            {
                System.out.println(i + ":0" + j);
            }
            else if(!(i == 0 && j == 60) && (j < 56 && i == 1))
            {
                System.out.println(i + ":" + j);
            }
            else if(i == 0 && j != 60)
            {
                System.out.println(i + ":" + j);
            }

            if(i == 0 && j == 60)
            {
                System.out.println("1:00");
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
        }
    }

Currently the output is something like:

1:55
1:54
1:53 
.
.
.

Is is possible to display the whole countdown in only one line. Not consecutively but the new println() overdisplays the old one like this:

1:55 (this display is overridden 1 seconds later by 1:54 and so on)

I would appreciate any help. Thanks

MageD

Edit: So it works with the /r command but only in the CMD of Windows itself. Maybe its a bug or so, but it answers my question. Thank you :)


Solution

  • Yes, use print rather than println and add a "\r" at the end of each output:

    e.g. System.out.println(i + ":0" + j + "\r");

    When you use println it does 2 things: moves onto the next line (line feed) and returns the cursor to the start of the line (carriage return). Think of it like a typewriter :-)

    If you manually print "\r" (just the carriage return) without advancing to the next line then the next thing you print will overwrite the previous contents of the line.