Scanner nextLine() skipped after nextInt() (Java) — how to fix
Enter your age: 25
Enter your name:
Hello, !
Quick fix: Call an extra scanner.nextLine(); after nextInt() to consume the leftover newline, or read every line with nextLine() and convert it: int age = Integer.parseInt(scanner.nextLine().trim());.
What it means
When the user types 25 and presses Enter, the input buffer contains 25\n.
nextInt()reads the token25and stops. The\nis still in the buffer.nextLine()returns everything up to the next line break. The very next character is that\n, so it returns an empty string immediately, without waiting for the user.
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.print("Enter your name: ");
String name = sc.nextLine(); // returns "" immediately
System.out.println("Hello, " + name + "!");
There's no exception. The program just seems to skip a prompt. The same happens after nextDouble(), nextLong(), nextBoolean() and next().
Fix 1: consume the rest of the line
Add a nextLine() call right after the numeric read:
int age = sc.nextInt();
sc.nextLine(); // discard the leftover newline
System.out.print("Enter your name: ");
String name = sc.nextLine();
This is the smallest change. It also throws away anything else typed on the same line, such as 25 years.
Fix 2: read whole lines and parse them (recommended)
Reading every input with nextLine() avoids the problem completely and makes validation easy:
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = Integer.parseInt(sc.nextLine().trim());
System.out.print("Enter your name: ");
String name = sc.nextLine();
With validation in a loop:
int age;
while (true) {
System.out.print("Enter your age: ");
String line = sc.nextLine().trim();
try {
age = Integer.parseInt(line);
break;
} catch (NumberFormatException e) {
System.out.println("Please enter a whole number.");
}
}
Use Double.parseDouble(...) for decimals. A non-numeric line throws NumberFormatException instead of the InputMismatchException you get from nextInt().
Fix 3: use next() if you only need one word
If the name can't contain spaces, next() skips leading whitespace (including the leftover newline) and reads one token:
int age = sc.nextInt();
String name = sc.next(); // "Ada" from "Ada Lovelace", rest stays in the buffer
For full names or sentences, stick with Fix 1 or Fix 2.
Related pitfalls
- Don't create a new Scanner for each read. Several Scanners on
System.ineach buffer input, so data gets lost. Create one Scanner and pass it around. - Don't close a Scanner on
System.inhalfway through. Closing it closesSystem.in, and every later read throwsNoSuchElementException. - Reading a file with mixed numbers and text? The same rule applies. After
nextInt(), the rest of the line, including its newline, is still waiting to be read.
Last updated 2026-12-04.