Creating Scanner
Description
Scanner can read from System.in.
Explanation
Import java.util.Scanner before using it.
Example
Scanner input = new Scanner(System.in);← Chapter 7 — Input, Wrappers & Lambdas
mixed
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.
Scanner can read from System.in.
Import java.util.Scanner before using it.
Scanner input = new Scanner(System.in);Methods such as nextLine and nextInt read input.
nextLine reads a full line, including spaces.
String name = input.nextLine();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.
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);
}
}