Scanner Class
1. What It Is (beginner)
Scanner breaks input into tokens (words/numbers) and converts to your type. Easiest keyboard reader: new Scanner(System.in). Lives in java.util (import needed!).
2. Full Method Map (exam table)
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 42
double d = sc.nextDouble(); // 3.14
String w = sc.next(); // one word (stops at space!)
String line = sc.nextLine(); // full line!
char c = sc.next().charAt(0);// first char
boolean b = sc.nextBoolean(); // true/false
Check first: hasNextInt() → true if next token is int (avoid crash!).
3. Complete Program (copy-paste safe pattern)
import java.util.Scanner;
public class Scan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("name age: "); // input: Asha 20
String name = sc.next(); // Asha
int age = sc.nextInt(); // 20
sc.nextLine(); // eat newline!
System.out.print("city: ");
String city = sc.nextLine(); // New Delhi (spaces ok!)
System.out.printf("Hi %s (%d) from %s%n", name, age, city);
sc.close();
}
}
4. Traps (all beginners hit these!)
- No import →
cannot find symbol. nextInt()+nextLine()→ empty line (eat newline!).next()stops at space (Asha Kumar→Ashaonly).- Two Scanners on
System.in→ weird skips (use ONE). abcfornextInt()→InputMismatchException.
5. Exam Points
- Method table + full program — 7 marks, very frequent.
- Newline trap + fix — 5 marks, all-time favourite.