5.11 Reading User Input
This lesson builds a small Java program that reads input from the keyboard. The class we use is Scanner from java.util.Scanner. We instantiate it with Scanner scanner = new Scanner(System.in);: new creates a fresh instance and System.in is the standard input stream.
We then prompt the user with System.out.println("Enter your name:"); and capture the reply with String name = scanner.nextLine();. The method nextLine() blocks until the user types something and presses Enter; the typed string is then assigned to the name variable. Printing "Your name is " + name echoes it back.
Reading an int and computing an age
- Prompt with
"Enter your birth year:". - Read an integer with
int birthYear = scanner.nextInt();. - Compute the age with
int age = 2021 - birthYear;and concatenate the message"You are " + age + " years old". - End with
scanner.close();to release the underlying stream.
One subtle detail: after nextInt() the cursor stays on the same line, so a follow-up nextLine() reads an empty string. Calling an extra scanner.nextLine(); after nextInt() consumes that leftover newline. With these few lines you have a Java program that talks to its user instead of staying silent.