是否可以在 Java 中仅在一个输出中显示 for 循环的结果?

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

我有一些代码可以在控制台中显示倒计时。

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) {}
        }
    }

目前的输出是这样的:

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

是否可以在一行中显示整个倒计时。不是连续的,而是新的 println() 像这样过度显示旧的:

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

如有任何帮助,我将不胜感激。 谢谢

法师D

编辑:因此它可以与 /r 命令一起使用,但只能在 Windows 本身的 CMD 中使用。也许它是一个错误左右,但它回答了我的问题。谢谢:)

你可以试试这个:Java: Updating text in the command-line without a new line

您可以使用“\r”来回车 Return,而无需使用 \n,这是一个换行符。回车 return 应该让你回到行首。

是的,使用print而不是println,并在每个输出的末尾添加一个"\r"

例如System.out.println(i + ":0" + j + "\r");

当您使用 println 时,它会做两件事:移动到下一行(换行)和 return 将光标移动到行首(回车 return) .把它想象成一台打字机:-)

如果您手动打印 "\r"(只是回车 return)而没有前进到下一行,那么您打印的下一个内容将覆盖该行之前的内容。

您想向您的终端写入一些东西(例如 1:59),然后擦除它并用其他东西覆盖它(例如 1:58)?如果是这样,那么没有简单的方法可以使用常规 System.out 方法来做到这一点。您需要了解 control characters for your OS and terminal type, or possibly use a library such as one of those suggested here(我没有尝试过,它们正是 Google 返回给我的)。

您正在寻找 Curses 图书馆。

Most implementations of curses use a database that can describe the capabilities of thousands of different terminals. There are a few implementations, such as PDCurses, which use specialized device drivers rather than a terminal database. Most implementations use terminfo; some use termcap.

有一些 Java Curses 库在 What's a good Java, curses-like, library for terminal applications?

这看起来可能很多,但除此之外,您将需要一个自己的终端功能数据库来实现该功能。