5

I have a BufferedReader waiting for input, but for some reason it doesn't wait for the second read and continues to print my third print statement.

Code:

BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
char letter,xVal;
int yVal;


System.out.println("Please enter a letter for your word.(a-z)");
letter=(char)inFromUser.read();  
System.out.println("Please enter a X location for this piece.(A-J)");
xVal=(char)inFromUser.read();
System.out.println("Please enter a Y location for this piece.(0-9)");
yVal=inFromUser.read();

Example execution goes as follows: Please enter a letter for your word. //Waits on input here

a

Please enter a X location for this piece. //Doesn't wait here???

Please enter a Y location for this piece.

1
  • Both answers work perfectly and explain what I was doing incorrectly. Thanks for the help guys! Commented Dec 4, 2012 at 1:51

2 Answers 2

5

This is happening because once you press enter after typing a letter, you are also sending the newline character into the stream.

When you call read() the first time it returns the first character as expected. However, when you call read() the second time it will simply read in the newline character that is buffered in the stream, thereby seeming like it skipped over a read instruction.

The solution is to tell the BufferedReader to read the entire line, then fetch the first character from the line:

System.out.println("Please enter a letter for your word.(a-z)");
letter = inFromUser.readLine().charAt(0);

You may also want to improve upon this by doing some validation in case the user simply presses enter without inputting a letter.

Sign up to request clarification or add additional context in comments.

Comments

5

The reason why it was not waiting is because xVal=(char)inFromUser.read(); was reading the "\n" from the line letter=(char)inFromUser.read();

So one solution it to add an inFromUser.readLine(); after each prompt:

    System.out.println("Please enter a letter for your word.(a-z)");
    letter=(char)inFromUser.read(); 
    inFromUser.readLine(); 
    System.out.println("Please enter a X location for this piece.(A-J)");
    xVal=(char)inFromUser.read();
    inFromUser.readLine();
    System.out.println("Please enter a Y location for this piece.(0-9)");
    yVal=inFromUser.read();
    inFromUser.readLine();

You add a inFromUser.readLine(); after each prompt, so it can read the "\n".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.