按 enter 继续奇怪 (Java)

Press enter to continue oddities (Java)

我正在使用此代码输出文本并让用户按 enter 以显示下一行对话框。但是,按一次 Enter 会显示两行文本。这是为什么?

public void pressEnterToContinue() {
    try {
        System.in.read();
    } catch(Exception e) { }
}

作为参考,该方法是这样调用的:

pressEnterToContinue();
System.out.println("This is a line of text.");
pressEnterToContinue();
System.out.println("So is this.");
pressEnterToContinue();
System.out.println("And this.");
//etc.

第一行单独显示 "This is a line of text." 该方法等到用户按下 enter,然后显示接下来的两行("So is this." 和 "And this."),而它应该只显示一行.

我确实尝试过实现短暂的延迟,但这并没有解决问题。

按回车键作为新行回显。 println 引入了另一行。当您在控制台键入时,O.S。回显每个字符,因此,您的输入被回显,然后您的代码再次将其打印在屏幕上。之所以如此,是因为您正在处理一个 shell,它本身就是一个程序,可以接收您的击键并回显它们。

可以编写一个 shell,它不会回显用户输入,但对于容易犯错的人来说是不切实际的。您可能想在各自的端口上尝试远程登录到 smtp 服务器或 http 服务器,然后键入适当的命令来发送邮件或返回 html 页面。那里没有回声。感觉怪怪的。

System.in.read() 读取一个字节。我的猜测是你 运行 你的代码在一个平台上,换行符由一个双字节的 CR LF 序列表示,所以按下 Enter 键满足第一个 System.in.read() 使用 CR 的调用,第二个 System.in.read() 用低频调用。将您的代码更改为使用 System.console().readline() 应该可以解决此问题,但也请检查 discussion and other approaches described here, and the solutions discussed here

这里 link 提供了有关换行符在各种平台上的表示方式的信息。