Phase 4 of 20 · Topic 4.1

Scanner Class & Delimiter-Based Parsing

1Concept

java.util.Scanner breaks its input into tokens using a delimiter pattern (default whitespace). It provides methods like nextInt(), nextDouble(), and nextLine() with automatic type parsing and regex support.

2Architecture Diagram

[ Input Stream: "Alice 28 95000.50\n" ]
       |
       v
[ Scanner Tokenizer (Delimiter: whitespace) ]
  Token 1: "Alice"   ---> scanner.next() (String)
  Token 2: "28"      ---> scanner.nextInt() (int)
  Token 3: "95000.5" ---> scanner.nextDouble() (double)

3Code Example

Core Java
import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        String simulatedInput = "JohnDoe 32 150000.75 Active";
        Scanner scanner = new Scanner(simulatedInput);

        String name = scanner.next();
        int age = scanner.nextInt();
        double salary = scanner.nextDouble();
        boolean active = scanner.nextBoolean();

        System.out.println("Parsed Employee: " + name);
        System.out.println("Age: " + age + " | Salary: $" + salary);
        System.out.println("Status: " + (active ? "Employed" : "Inactive"));
        scanner.close();
    }
}

4Expected Output

Parsed Employee: JohnDoe
Age: 32 | Salary: $150000.75
Status: Employed

5Key Takeaways

  • Beware of the nextLine() trap: calling nextLine() after nextInt() reads the leftover newline character.
  • Scanner is synchronized and parses with regex, making it slower than BufferedReader for large datasets.
  • Always close the Scanner to release the underlying input stream.