Skip to content
AgileLogics
4 min read

Reading User Input

Prerequisites: String formatting

Scanner reads input typed by the person running the program:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("What's your name? ");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name + "!");
    }
}

Common mistakes

  • Mixing nextInt() with nextLine() — nextInt() doesn't consume the newline character left behind, so a following nextLine() call can appear to be skipped. Call scanner.nextLine() once extra to consume it, or use nextLine() everywhere and parse manually.