Workbook 1c, pp. 82-86 — Why nextInt() and nextLine() don't play nice
Buggy Code
Scannerscanner = newScanner(System.in);System.out.println("Enter your age: ");intage = scanner.nextInt();System.out.println("Enter your name: ");Stringname = 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
Scannerscanner = newScanner(System.in);System.out.println("Enter your age: ");intage = scanner.nextInt();scanner.nextLine(); // consume the leftover \nSystem.out.println("Enter your name: ");Stringname = 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().