← Chapter 7 — Input, Wrappers & Lambdas

27. User Input with Scanner

mixed

Description

Scanner reads text and simple values from an input source, including the keyboard. It is a convenient starting point for interactive command-line programs.

Prompt users clearly and validate input in larger programs. Remember that reading a number and then a line requires care because the line break remains in the input buffer.

Subtopics

Creating Scanner

Description

Scanner can read from System.in.

Explanation

Import java.util.Scanner before using it.

Example

Scanner input = new Scanner(System.in);

Reading values

Description

Methods such as nextLine and nextInt read input.

Explanation

nextLine reads a full line, including spaces.

Example

String name = input.nextLine();

Explanation

For a short console example, do not close a Scanner that wraps System.in if more code still needs standard input. In application code, manage resource ownership deliberately.

Example

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = input.nextLine();
        System.out.println("Welcome, " + name);
    }
}

Key points

  • Scanner reads user input.
  • nextLine reads a complete line.
  • Import java.util.Scanner.

Video

Open video

Open reference