TExcelTAD
Home › Java › Java User Input

Java User Input

Interactive console programs read what the user types. In Java the easiest way to do this is the Scanner class from the java.util package. A Scanner wraps an input source — usually the keyboard, System.in — and splits it into pieces called tokens that you can read as strings, numbers or whole lines.

Note: Playgrounds on ExcelTAD can't pause to wait for typing, so the keyboard examples below are shown without a Run button. The runnable examples give Scanner a fixed String instead — the reading methods behave exactly the same.

Reading from the keyboard

java
import java.util.Scanner;

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

        System.out.print("What is your name? ");
        String name = input.nextLine();

        System.out.print("How old are you? ");
        int age = input.nextInt();

        System.out.println("Hello " + name + ", next year you will be " + (age + 1));
        input.close();
    }
}

A sample session (user typing shown after the prompts):

What is your name? Maria
How old are you? 31
Hello Maria, next year you will be 32

Steps to remember:

  1. import java.util.Scanner; at the top of the file.
  2. Create one Scanner for System.in and reuse it.
  3. Print a prompt with print so the cursor stays on the same line.
  4. Call the method that matches the type you expect.

Scanner methods

Method Reads
nextLine() the rest of the current line as a String
next() the next word (up to whitespace)
nextInt() an int
nextDouble() a double
nextBoolean() a boolean
nextLong() a long
hasNext() / hasNextInt() / hasNextLine() true if another token (of that type) is available

Trying the methods on fixed text

A Scanner can read from a String just like from the keyboard. This lets us demonstrate the methods with predictable output:

java · try it yourself
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner("Ada 36 1.75 true");
        String name = sc.next();
        int age = sc.nextInt();
        double height = sc.nextDouble();
        boolean likesMath = sc.nextBoolean();
        System.out.println(name + " is " + age + ", " + height + " m tall, likes maths: " + likesMath);
    }
}
Ada is 36, 1.75 m tall, likes maths: true

Reading until the input ends

hasNextInt() and hasNextLine() let you process an unknown amount of input safely:

java · try it yourself
import java.util.Scanner;

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

        Scanner lines = new Scanner("first line\nsecond line\nthird line");
        int n = 1;
        while (lines.hasNextLine()) {
            System.out.println(n++ + ": " + lines.nextLine());
        }
    }
}
4 numbers, sum 54
1: first line
2: second line
3: third line

The nextInt / nextLine trap

nextInt() reads the number but leaves the line break in the input. A following nextLine() then returns that empty leftover instead of waiting for new text:

java · try it yourself
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner("42\nBob Smith\n");
        int id = sc.nextInt();
        String leftover = sc.nextLine();   // just the "\n" after 42
        String name = sc.nextLine();
        System.out.println("id=" + id + ", leftover=[" + leftover + "], name=" + name);
    }
}
id=42, leftover=[], name=Bob Smith

The fix is to call an extra nextLine() after nextInt() (as above), or to read every line with nextLine() and convert with Integer.parseInt.

Handling bad input

If the user types abc where a number is expected, nextInt() throws an InputMismatchException. Check with hasNextInt() first, or catch the exception:

java · try it yourself
import java.util.InputMismatchException;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner("abc 15");
        try {
            int value = sc.nextInt();
            System.out.println("Got " + value);
        } catch (InputMismatchException e) {
            System.out.println("That was not a number: " + sc.next());
        }
        System.out.println("Next number: " + sc.nextInt());
    }
}
That was not a number: abc
Next number: 15

Test yourself

Which import is needed to use Scanner?

  1. import java.io.Scanner;
  2. import java.util.Scanner;
  3. import java.lang.Scanner;
  4. No import needed

Input is Hello World. What does sc.next() return?

  1. Hello World
  2. Hello
  3. World
  4. H

Why might nextLine() return an empty string right after nextInt()?

  1. Scanner is broken
  2. nextInt leaves the line break unread
  3. nextLine only reads numbers
  4. The input was closed