← Back to Week 1 Hub

Scanner Buffer / CRLF Problem

Workbook 1c, pp. 82-86 — Why nextInt() and nextLine() don't play nice

Buggy Code

Scanner scanner = new Scanner(System.in); System.out.println("Enter your age: "); int age = scanner.nextInt(); System.out.println("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello " + name + ", age " + age);
age ?
name ?

Input Buffer

System.in buffer
Press Next Step to walk through the code line by line.

Console Output

Waiting...

Fixed Code

Scanner scanner = new Scanner(System.in); System.out.println("Enter your age: "); int age = scanner.nextInt(); scanner.nextLine(); // consume the leftover \n System.out.println("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello " + name + ", age " + age);
age ?
name ?

Input Buffer

System.in buffer
Press Next Step to see how the fix works.

Console Output

Waiting...

The Golden Rule

After nextInt(), nextDouble(), or nextFloat(), always add an extra scanner.nextLine() to consume the leftover newline character before reading a String.

Alternative Approach

Some developers avoid this problem entirely by reading everything as strings with nextLine() and parsing numbers manually with Integer.parseInt() or Double.parseDouble().

← printf Format Specifiers if/else Flowchart →