Home › Java

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.

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.

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.

Last updated 2026-12-04.