Search code examples
javaentercontinue

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. However, one press of Enter shows two lines of text. 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.

I did try implementing a short delay but that didn't solve the issue.


Solution

  • System.in.read() reads one byte. 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. 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.

    And here's a link to info about how newline is represented on a variety of platforms.