Java Scanner – How Does System.in Input Buffering Work?

java

Over the last days, I've being reading questions as the one that follows: "Why is my input code not working?" I myself had a couple times problems getting the input working right…

as far as good, i found a couple solutions to avoid the problem like typing nextLine() to flush the buffer. But I'm still not sure what am I doing.

I think that Scanner(somefile) looks simpler to understand to me, since every character (including space or enter) are written on the file. But does it work the same way when we get the input from the keyboard? When I ask for an Integer for example (using nextInt() ), and then I give the number in the command-line and press 'intro', why is that \n staying on the buffer?

Could anyone help us understand it by giving a step-by-step answer?

Best Answer

According to Java Docs: About nextInt()

Scans the next token of the input as an int. If the translation is successful, the scanner advances past the input that matched.

This method consumes the integer, but not the new-line character or other character after that integer. So after consumption of integer by nextInt(), there only remain newline character (In this case) as entered by keyboard or file. It cannot discarded by nextInt(). Thus \n staying on the buffer.

And description of nextLine() says

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

As we expected by nextLine(), it consumes the new-line character that was not consumed by nextInt(). But when it return it exclude newline so returned string by nextLine() becomes empty.

Related Topic