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!");
}
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");
}
}
You can also do 10 if you like, but I prefer using 13. Hope this helps!