Reading User Input (Scanner)
To build interactive programs, we need to read values from the console. Java provides the Scanner class inside the java.util package to capture standard input streams.
1 Scanner Methods & Buffer Flushing issues
The `Scanner` class provides different methods for reading data types:
- `nextInt()`: Reads the next integer tokens.
- `nextDouble()`: Reads decimal tokens.
- `next()`: Reads a single word token (stops at spaces).
- `nextLine()`: Reads an entire line of text including spaces.
⚠️ Critical Gotcha: The Newline Buffer Issue
When you input a number and press Enter (e.g. `nextInt()`), Java reads the number token but leaves the trailing newline character (`\n`) sitting in the buffer. If you subsequently call `nextLine()`, it instantly consumes that leftover newline and returns empty text without waiting for user input. To fix this, always call a dummy `scanner.nextLine()` to "flush" the buffer after reading numbers before reading strings.
2 Interactive Scanner Code
Let's run a program that reads name, age, and details safely with proper buffer flushes:
Java — Scanner Input
▶ Run Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Setup scanner reading standard input stream
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your Age: ");
int age = scanner.nextInt();
// 🚨 CRITICAL: Flush the newline character from the buffer!
scanner.nextLine();
System.out.print("Enter your Full Name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
// Good practice: Close the resource streams
scanner.close();
}
}
3 Code Challenge
Challenge: Write an interactive calculator program. Use Scanner to ask the user to input two numbers, and then input their choice of operator (`+`, `-`, `*`). Compute and print the result. Use a buffer flush appropriately if you read numbers before strings/chars.