CodeMIRAI
0 XP

Reading input with Scanner

2 min read 6 runnable examples Quiz included

Scanner reads text from the keyboard, or from whatever input the program is given. Each example in this lesson comes with its input, named in the text above it. To try your own, press Playground and type it into the Input box.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String name = in.nextLine();
        System.out.println("Hello, " + name + "!");
    }
}

That example ran with the input Asha Verma.

  • import java.util.Scanner; makes the class available; it lives in the java.util package.
  • new Scanner(System.in) reads from standard input.
  • Create one Scanner for System.in and reuse it everywhere.

Words and numbers

This one runs with the input Mei 21 1.62:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String name = in.next();           // one word
        int age = in.nextInt();
        double height = in.nextDouble();
        System.out.println(name + " is " + age + " and " + height + " m tall");
        System.out.println("In ten years: " + (age + 10));
    }
}

Items can be separated by spaces or line breaks: next(), nextInt() and nextDouble() skip over whitespace to find the next one.

MethodReads
nextLine()the rest of the current line, as a String
next()the next word
nextInt(), nextLong()the next whole number
nextDouble()the next decimal number
nextBoolean()true or false

The nextInt-then-nextLine trap

The input here is 21, a line break, then Asha Verma:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int age = in.nextInt();
        String name = in.nextLine();      // oops: reads what's left of the "21" line
        System.out.println("age=" + age + ", name=[" + name + "]");
    }
}

nextInt() reads 21 but leaves the line break after it. nextLine() then returns the rest of that line, which is empty. Finish the number's line before reading the next one:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int age = in.nextInt();
        in.nextLine();                    // discard the rest of the number's line
        String name = in.nextLine();
        System.out.println("age=" + age + ", name=[" + name + "]");
    }
}

Another common fix is to read every line with nextLine() and convert numbers with Integer.parseInt(line.trim()).

Reading until the input runs out

Input: four numbers, one per line.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = 0, sum = 0;
        while (in.hasNextInt()) {
            sum += in.nextInt();
            count++;
        }
        System.out.println(count + " numbers, total " + sum);
    }
}

hasNextInt() checks whether another whole number is waiting, without reading it. It returns false at the end of the input, or when the next item isn't a number.

Checking before reading

Input: the word twelve, then 12.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your age:");
        while (!in.hasNextInt()) {
            String bad = in.next();
            System.out.println("'" + bad + "' isn't a number. Try again:");
        }
        int age = in.nextInt();
        System.out.println("Thanks. Age: " + age);
    }
}

Calling nextInt() on twelve would crash the program with an InputMismatchException. Checking with hasNextInt() first lets it ask again instead.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.