Introduction to Java · Introduction to Java Programming

Scanner Class

Watch lectures

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 → Asha only).
  • Two Scanners on System.in → weird skips (use ONE).
  • abc for nextInt() → InputMismatchException.

5. Exam Points

  • Method table + full program — 7 marks, very frequent.
  • Newline trap + fix — 5 marks, all-time favourite.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules