按Enter键触发System.in.read()两次? [英] Pressing Enter Triggers System.in.read() twice?

查看:99
本文介绍了按Enter键触发System.in.read()两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,每当我在 System.in.read()中使用 ENTER 键时循环后,代码立即执行两次。如果它不在循环中,它将执行一次!这是为什么?

For some reason, whenever I press the ENTER key when using System.in.read() in a loop, the code immediately afterwards executes twice. If it isn't in a loop, it will execute once! Why is this?

这是一个测试它的代码片段:

Here is a code snippet to test it:

while(true) {
    System.in.read();
    System.out.println("I am supposed to print once, but I print twice!");
}


推荐答案

你有这个原因发生的原因是当你按Enter键时,System.in.read()将注册两个字符。这应该被用作更复杂的扫描程序版本,而不是使用扫描程序,你将执行Scanner.nextLine()或Scanner.nextInt(),它将返回一个字符串或整数,它返回一切为char码。例如,如果我输入a并按回车键,则会将97,13和10打印到控制台。但是如果你通过使用(char)97将它转换为char来转换第一个数字(97),你会得到一个a。现在,如果你看看最后两个,那就是输入按钮。 13是按下的输入按钮,10是当释放输入按钮时创建新的换行。因此,无论何时按下按钮,都会触发System.in.read(),从而在循环中运行代码。但是,当你发布时它也会再次执行它,因为你刚刚通过释放enter按钮再次触发它,这也触发了System.in.read()。所以,为了解决这个问题,请执行以下操作:

The reason you are having this happen is because when you press enter, System.in.read() will register two chars. This is supposed to be used as a more complex version of scanner, instead of using a scanner where you would do Scanner.nextLine() or Scanner.nextInt() where it would return a string or a integer, it returns everything as a char code. For example, if I were to type "a" and press enter, it would print out 97, 13, and 10 to the console. But if you converted the first digit (97) by casting it to a char using (char) 97, You would get a "a" back. Now, if you look at the last two, those are the enter button. 13 is the enter button being pressed, and 10 is the creation of a new line feed when the enter button is being release. So, whenever you press down the button, that will trigger System.in.read() and thus, run the code in the loop. But, it will also do it again when you release, because you have just triggered it again by releasing the enter button, which also triggers the System.in.read(). So, in order to fix this, do this:

while(true) {
    if(System.in.read() == 13) {
        System.out.println("I now only execute once like I should! :D");
    }
}

如果你愿意,你也可以做10,但我喜欢使用13.希望这有帮助!

You can also do 10 if you like, but I prefer using 13. Hope this helps!

这篇关于按Enter键触发System.in.read()两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆