[!NOTE] A program isn't very interactive if it only talks to itself. The
Scannerclass allows your application to pause execution and wait for the user to type something on their keyboard.
Importing and Setting Up Scanner
The Scanner class is not loaded by default to save memory. You must actively import it from the java.util package.
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args) {
// 1. Create a Scanner object hooked up to the System Input stream (keyboard)
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username:");
// 2. Pause the program and wait for the user to hit Enter
String userName = myObj.nextLine();
System.out.println("Welcome, " + userName + "!");
// 3. Close the scanner when done!
myObj.close();
}
}
[!CAUTION] Always remember to call
.close()on your Scanner when your program finishes. Leaving input streams open can cause resource memory leaks.
Reading Different Data Types
The Scanner has different methods corresponding to the primitive data type you want to read.
| Method | Description |
|---|---|
.nextLine() |
Reads a String value (the entire line including spaces). |
.nextInt() |
Reads an int value. |
.nextDouble() |
Reads a double value. |
.nextBoolean() |
Reads a boolean value. |
The "Scanner Bug"
- Newline Artifacts
A very common trap for beginners: If you read an integer, and then immediately try to read a string, it will skip the string! Why? Because nextInt() only reads the number, leaving the "Enter" keypress (newline character) sitting in the buffer. The subsequent nextLine() immediately swallows that newline and finishes.
The Fix: Manually fire a blank nextLine() after reading numbers to clear the buffer.
System.out.println("Enter age:");
int age = scanner.nextInt();
// The Fix! Clear out the leftover 'Enter' key press
scanner.nextLine();
System.out.println("Enter name:");
String name = scanner.nextLine();