AP® Computer Science A · Unit 1 · Topic 1.4

Reading Input with a Scanner

A Scanner reads input by pulling one token at a time off the keyboard stream, converting it to the type you ask for. The catch: it only reads exactly what you ask for, leaving everything else, including the leftover newline, sitting in the stream for the next call.

A program can't just absorb whatever a user types. Keystrokes arrive as a stream of raw characters, and someone has to decide where one piece of data ends and the next begins, then convert text like "42" into an actual int. That's the Scanner's job: you hand it a source, usually System.in, and it hands back tokens, one call at a time, already converted to the type you asked for.

Every Scanner call works the same way: look at the stream, skip leading whitespace, read characters until the next whitespace or newline, and return just that chunk. nextInt() reads digits and stops the instant it hits a non-digit character, including the newline produced when the user hits enter. It does not consume that newline. nextDouble() behaves the same way for decimals. nextLine() is different: it reads everything up to and including the next newline, so it returns whatever text sits between where the cursor is and the end of the line, even if that's nothing at all.

That difference is exactly why nextInt() followed by nextLine() surprises people. The nextInt() call grabs the number and quits, leaving the trailing newline sitting unread in the stream. The very next nextLine() call immediately finds that leftover newline, decides the line is already over, and returns an empty string instead of waiting for new input. This matters once programs mix numeric input with text input, like reading an age and then a full name, which is exactly where this bug shows up.

Key terms

Scanner
A Java class that reads and parses tokens from an input source such as System.in.
token
A chunk of input separated from the rest by whitespace, such as a single word or number.
input stream
The ongoing sequence of characters a program receives from a source like the keyboard.
nextInt
A Scanner method that reads the next token as digits and converts it to an int, stopping before the trailing newline.
nextLine
A Scanner method that reads all characters up to and including the next newline, possibly returning an empty string.

Watch it explained

  1. How it worksHow does a Scanner pull tokens off the input stream one call at a time?
  2. Worked exampleTrace what nextInt and then nextLine read when a user types 42 and presses enter.
  3. Common mistakeWhy doesn't nextLine after nextInt pick up the line you actually meant to type?
  4. Going furtherWhat happens when nextInt meets input that is not a number at all?

Check yourself

Your turn1 of 2
A program calls sc.nextInt() then immediately sc.nextLine(), and the user types 42 and presses enter. What does the nextLine() call return?

End of topic.