0

I have a code where I want to print counters in the same output line. It is supposed to be like this: a name (that is fixed) and the seconds would be running until 0 on its side.

The following code is what I have now:

public void CountdownToZero(String name, int secs) {
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = secs;
    System.out.print(name +" "+ secs);
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            System.out.print(name + " " + setInterval());
        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}

And the actual output is:

name 5
name 4
name 3
name 2
name 1
name 0

And what I'd want to appear on the output would be:

name [countdown seconds to 0]
name1 [countdown seconds to 0]
name2 [countdown seconds to 0]

Can someone help me in this case? Thanks in advance!

  • Are you saying that you have _N_ output lines, and for each line, you want to adjust the count down timer? In the console? – KevinO Oct 18 '18 at 19:10
  • If I understand the question correctly, you could just change your `print` to include whatever you want. – Robert Oct 18 '18 at 19:11
  • @KevinO I just put the multiple output lines as my final goal in this code, because I thought it was better to understand how it would look in a final version. For now, I just wanted to print the countdown timer, with the seconds going down, in the same line, kinda overwriting the previous second with a -1 sec – Alexandre Ferreira Oct 18 '18 at 19:18
  • @Robert I tried to use `print` and the output I got was `name 5name 4name 3name 2name 1name 0` – Alexandre Ferreira Oct 18 '18 at 19:19
  • If you printed `name 5` there is no way to delete it from screen and replace with `name 4` – Ivan Oct 18 '18 at 19:22
  • Generally, the console doesn't have a concept of location. It _might_ be possible with ANSI control codes, but that could be limited. Generally, you either use a GUI (really, that's what Java was designed for), or you can try a library such as JCurses. [But essentially this question is therefore a duplicate](https://stackoverflow.com/questions/1001335/java-gotoxyx-y-for-console-applications) – KevinO Oct 18 '18 at 19:24
  • I kept looking for some solutions and I found a topic where it says that I could put `\r` to bring the cursor back in console to the first position and overwrite what was printed... Is it a valid solution? Or it works in other kind of way? – Alexandre Ferreira Oct 18 '18 at 19:29

0 Answers0