简体   繁体   English

按Enter继续进行奇数运算(Java)

[英]Press enter to continue oddities (Java)

I'm using this code to output text and have the user press enter to show the next line of dialog. 我正在使用此代码输出文本,并让用户按Enter键以显示对话框的下一行。 However, one press of Enter shows two lines of text. 但是,按Enter键会显示两行文本。 Why is this? 为什么是这样?

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

For reference, the method is called like this: 作为参考,该方法的调用方式如下:

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

The first line displays alone "This is a line of text." 第一行仅显示“这是文本行”。 The method waits until the user presses enter, then it displays the next two lines ("So is this." and "And this.") when it should display only one. 该方法一直等到用户按下Enter键,然后在仅显示一行时显示接下来的两行(“ So is this。”和“ And this。”)。

I did try implementing a short delay but that didn't solve the issue. 我确实尝试过实施短暂的延迟,但这并不能解决问题。

Pressing the enter key echoes back as a new line. 按下Enter键回显为新行。 println introduces yet another line. println引入了另一条线。 As you type at a console, the OS echoes back each and every character, and as such, your input is echoed back and then your code prints it again on the screen. 当您在控制台上键入内容时,操作系统将回显每个字符,因此,您的输入将被回显,然后您的代码将其再次打印在屏幕上。 This is so because you are dealing with a shell which is itself a program that pick up your keystrokes and echoes them back. 之所以如此,是因为您要处理的外壳程序本身就是一个程序,可以拾取击键并回显它们。

A shell could be written that does not echo back the user input but would be impractical for fallible humans. 可以编写一个不会回显用户输入但对于易犯错误的人来说是不切实际的外壳。 You might want to experiment telneting to a smtp server or http server on their respective port and type the appropriate commands to send mail or get a html page back. 您可能要尝试在各自端口上对smtp服务器或http服务器进行telnet,然后键入适当的命令以发送邮件或获取html页面。 No echo there. 那里没有回声。 It feels weird. 感觉很奇怪。

System.in.read() reads one byte. System.in.read()读取一个字节。 My guess is you are running your code on a platform where a newline is represented by a two byte CR LF sequence, so pressing the Enter key satisfies the first System.in.read() call with the CR, and the second System.in.read( ) call with the LF. 我的猜测是,您正在一个以两个字节的CR LF序列表示换行符的平台上运行代码,因此按Enter键可以满足CR的第一个System.in.read()调用和第二个System.in.read(用LF调用System.in.read( )。 Changing your code to use System.console().readline() instead should fix this, but do check out the discussion and other approaches described here , and the solutions discussed here as well. 更改您的代码以使用System.console().readline()可以解决此问题,但请查看此处讨论的内容和其他方法 ,以及此处讨论解决方案

And here's a link to info about how newline is represented on a variety of platforms. 这是有关在各种平台上如何表示换行符的信息的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM