How to Use Scanner in Java to Read Input

Scanner is the standard way to read input in Java console programs. Wrap it around System.in to read keyboard input, or around a File or String to parse data.

Basic usage

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = sc.nextLine();

        System.out.print("Enter your age: ");
        int age = sc.nextInt();

        System.out.printf("Hello, %s! You are %d years old.%n", name, age);

        sc.close();
    }
}

Scanner methods

MethodReadsStops at
nextLine()Entire line including spacesNewline (consumed)
next()Next token (word)Whitespace (not consumed)
nextInt()Next intWhitespace (not consumed)
nextDouble()Next doubleWhitespace (not consumed)
nextBoolean()true / falseWhitespace
hasNextLine()Returns true if more input

The newline trap (most common Scanner bug)

Scanner sc = new Scanner(System.in);

System.out.print("Enter age: ");
int age = sc.nextInt();          // reads "21", leaves "\n" in buffer

System.out.print("Enter name: ");
String name = sc.nextLine();     // reads the leftover "\n" — gives empty string!

// Fix: consume the leftover newline after nextInt:
System.out.print("Enter age: ");
int age2 = sc.nextInt();
sc.nextLine();                   // consume the "\n"
System.out.print("Enter name: ");
String name2 = sc.nextLine();    // now correctly reads the name

Reading until end of input (file or pipe)

Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    System.out.println("Line: " + line);
}
sc.close();

Scanning a String directly

Scanner sc = new Scanner("42 3.14 hello");
int n = sc.nextInt();       // 42
double d = sc.nextDouble(); // 3.14
String s = sc.next();       // hello
sc.close();

Scanning a file

import java.io.File;
import java.io.FileNotFoundException;

try (Scanner sc = new Scanner(new File("data.txt"))) {
    while (sc.hasNextLine()) {
        System.out.println(sc.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Using try-with-resources (try (Scanner sc = ...)) closes the scanner automatically, even if an exception is thrown.