4oursword
4oursword

Reputation: 75

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.

Upvotes: 1

Views: 2019

Answers (2)

Richard Schwartz
Richard Schwartz

Reputation: 14628

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.

Upvotes: 0

Tarik
Tarik

Reputation: 11209

Pressing the enter key echoes back as a new line. println introduces yet another line. As you type at a console, the O.S. 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. No echo there. It feels weird.

Upvotes: 2

Related Questions