Lesson 7 / 38

Console Input

Read keyboard input in Java with Scanner over System.in, use nextInt / nextDouble / nextLine, and avoid the classic leftover-newline bug.

Scanner

Wrap System.in in a Scanner. Use nextInt(), nextDouble(), nextLine() to read typed tokens. Close it when done (or use try-with-resources).

import java.util.Scanner;

try (Scanner in = new Scanner(System.in)) {
    System.out.print("Name: ");
    String name = in.nextLine();
    System.out.print("Age: ");
    int age = in.nextInt();
    System.out.printf("%s is %d%n", name, age);
}

The nextLine() trap

After nextInt(), the newline you pressed is still in the buffer, so the next nextLine() returns an empty string. Call an extra nextLine() to consume it.