Reading input with Scanner

Core Java · lesson 28 of 42 · 3 min read

Read text and numbers from a source, and dodge the classic nextInt/nextLine trap.

Open this lesson in the learning hub

Key points

  • new Scanner(System.in) reads the console. A Scanner over a String runs the same code in a test.
  • nextLine() takes the rest of the line, while next() and nextInt() take one token.
  • Check before you read: hasNextInt() avoids the InputMismatchException a stray word would cause.
  • nextInt() leaves the newline behind, so the next nextLine() comes back empty. Read lines and parse them.
  • Reading past the end throws NoSuchElementException, so drive the loop with hasNext().
  • Close it with try-with-resources — but never close a Scanner over System.in while you still need input.

Example

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // A real program uses new Scanner(System.in). A String source keeps this demo repeatable.
        String typed = "Ada\n36\nred green blue\n";

        try (Scanner in = new Scanner(typed)) {
            String name = in.nextLine();
            int age = Integer.parseInt(in.nextLine());
            System.out.println(name + " is " + age + " years old");

            String[] colours = in.nextLine().split(" ");
            System.out.println("read " + colours.length + " colours, first = " + colours[0]);
        }

        try (Scanner tokens = new Scanner("10 20 hello 30")) {
            int total = 0;
            while (tokens.hasNext()) {
                if (tokens.hasNextInt()) {
                    total += tokens.nextInt();
                } else {
                    System.out.println("not a number, skipping: " + tokens.next());
                }
            }
            System.out.println("total of the numbers: " + total);
        }

        System.out.println("nextInt() leaves the newline behind - that is why a later nextLine() looks empty");
    }
}

Guard every read with hasNextX, and prefer nextLine plus parse.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.