Scrivio Interview library
DebuggingFoundations5 min read · updated 12 November 2026

This code skips the name input:

Java
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
String name = sc.nextLine();

Explain why and fix it.

nextInt() reads the digits of the number but leaves the line break that the user typed after it in Scanner's buffer. The following nextLine() reads up to that line break, finds nothing before it, and returns an empty string, so the name prompt seems to be skipped. We fix it by calling nextLine() once after nextInt() to consume the rest of the line, or, more robustly, by reading every line with nextLine() and parsing numbers with Integer.parseInt.

Why this question is asked

This is probably the most common surprise for anyone writing their first interactive Java program, and it still turns up in internal tools and coding exercises. Interviewers ask it because the explanation shows whether we understand that Scanner works on a stream of characters with a cursor, not on "lines the user typed", and because the follow-up questions (bad input, closing System.in) catch people who only memorised the fix. In this answer, we will look at what Scanner keeps in its buffer, trace the broken code character by character, apply two fixes, handle non-numeric input correctly, and see why closing the Scanner can break the rest of the program.

1How Scanner Reads Its Input

Scanner reads characters from System.in into an internal buffer and keeps a position, a cursor, in that buffer. Each method moves the cursor. The token methods, next() and nextInt(), skip any delimiters (whitespace, which includes line breaks), read one token, and stop right after it. The line method, nextLine(), returns everything from the cursor up to the next line separator and moves the cursor past that separator.

When the user types 30 and presses Enter, the program receives the characters 3, 0 and a line break. Pressing Enter is part of the input, and that is the whole story of this bug.

2Tracing the Broken Code

Here is the code from the question with what each call sees when the user types 30, Enter, Asha, Enter.

Java
Scanner sc = new Scanner(System.in);
System.out.print("Age: ");
int age = sc.nextInt(); // reads "30"; the buffer still holds "\n"
System.out.print("Name: ");
String name = sc.nextLine(); // reads up to that "\n": returns "" immediately
System.out.println(age + " [" + name + "]"); // 30 []
Scanner's buffer after each call
CallReturnsLeft in the buffer
(user types 30, Enter)30\n
nextInt()30\n
nextLine()"" (empty)nothing; waits for more next time
Fix: extra nextLine()"" (discarded)nothing; next nextLine() waits for the name

nextInt() stops right after the 0, so the line break is still waiting. nextLine() does exactly what it promises: it returns the rest of the current line, which is empty, and consumes the line break. It does not wait for the user, because a complete line is already in the buffer. The program prints the name prompt and moves on before the user can type anything.

3Fix 1: Consume the Rest of the Line

The smallest fix is to throw away the remainder of the number's line before reading the name.

Java
int age = sc.nextInt(); // 30
sc.nextLine(); // consumes the "\n" left by nextInt()
String name = sc.nextLine(); // waits, then "Asha"
System.out.println(age + " [" + name + "]"); // 30 [Asha]

This works, but notice that it relies on the user typing nothing else on the age line. If they type 30 years and press Enter, nextInt() returns 30 and the extra nextLine() silently discards years, which may or may not be what we want.

4Fix 2: Read Lines, Then Parse

The more robust approach is to treat each answer as a line, because that is how people type, and convert it ourselves. Then there is never a leftover line break to worry about.

Java
System.out.print("Age: ");
int age = Integer.parseInt(sc.nextLine().trim()); // "30" -> 30
System.out.print("Name: ");
String name = sc.nextLine(); // "Asha"
System.out.println(age + " [" + name + "]"); // 30 [Asha]

Mixing token methods with nextLine() is where the trouble comes from, so a simple rule for interactive programs is to use one style throughout, and the line style is easier to reason about.

5Handling Input That Is Not a Number

There is a second trap. If the user types abc, nextInt() throws InputMismatchException, and it does not consume the bad token. A retry loop that just calls nextInt() again sees abc again and loops forever, printing the error each time.

Java
// Broken retry: abc is never consumed, so this loops forever
while (true) {
try { age = sc.nextInt(); break; }
catch (InputMismatchException e) { System.out.println("Please enter a number"); }
}
// Correct: check first, and skip the bad token
while (!sc.hasNextInt()) {
System.out.println("Please enter a number");
sc.next(); // discard "abc"
}
int age = sc.nextInt();
sc.nextLine(); // and still consume the line break

With the line-based style, the same loop catches NumberFormatException from Integer.parseInt, and since nextLine() has already consumed the line, a retry simply reads the next one.

6Why Closing the Scanner Can Break the Program

Scanner implements Closeable, so tools and IDEs suggest closing it. But closing a Scanner closes its source, and here the source is System.in. Once System.in is closed, any later Scanner on it gets NoSuchElementException when it tries to read, even though the user is still there. So we create one Scanner for System.in, share it, and do not close it while the program may still need input; letting the program exit closes standard input anyway.

7Follow-up questions

Does next() have the same problem as nextInt()?

Yes. Every token method, next(), nextInt(), nextDouble() and the others, stops right after the token and leaves the line break behind. Only nextLine() consumes it.

Would BufferedReader avoid this bug?

Yes, because BufferedReader only offers readLine(), so every read consumes a whole line. We then parse numbers with Integer.parseInt. It is also faster, which matters for large inputs.

Why does hasNextInt() not consume anything?

The hasNext methods only look ahead to decide what the next token is; they never move the cursor. That makes them safe for checking input, but it also means we must call next() to get rid of a token we do not want.

8Conclusion

In this answer, we saw that Scanner keeps a cursor in a buffer of characters, and that pressing Enter puts a line break into that buffer. nextInt() stops before the line break, so the next nextLine() returns an empty string. We fixed it by consuming the rest of the line, or better, by reading whole lines and parsing them, handled non-numeric input without an endless loop, and saw why a Scanner on System.in should not be closed while input is still needed.

What to say in the interviewAbout 80 seconds aloud

Open with

The user types 30 and presses Enter, so the input is 3, 0 and a newline. nextInt reads the token 30 and stops right after it, leaving the newline in Scanner's buffer. nextLine then returns everything up to the next newline, which is nothing, so it returns an empty string straight away without waiting, and it looks like the name was skipped.

Then, if they want more

The quick fix is an extra sc.nextLine() after nextInt to throw away the rest of that line. The fix I prefer is to read every answer with nextLine and convert numbers with Integer.parseInt, because then I never mix token reads and line reads and there is never a leftover newline. Two related things I would mention.

If the user types something that is not a number, nextInt throws InputMismatchException and does not consume the bad token, so a retry loop must call next() to skip it, or better check with hasNextInt first; with the line approach I catch NumberFormatException and simply read the next line.

And I would not close a Scanner that wraps System.in if anything else still needs input, because closing the Scanner closes System.in, and later reads fail with NoSuchElementException.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This code skips the name input:": https://scrivio-interview-library.netlify.app/java/io-and-nio/9647a93e35/