Scanner & Standard Input

The Course
•
5 min read

So far main has supplied fixed example values. Standard input lets a caller provide text without editing the calculation. In this browser, fill the input box before pressing Run. The Java program reads all of that supplied text; it does not pause for a new answer after printing a prompt. Prompts are ordinary output, and typed input is not echoed into that output.

Import java.util.Scanner, then create one Scanner over System.in. In Scanner input = new Scanner(System.in);, Scanner is the type, input is the variable name, and System.in is the source of the supplied text. The new call constructs a reader for that source. Calling input.nextLine() asks that reader for a line and moves its reading position forward. It can read space-separated tokens with nextInt or whole lines with nextLine. A token is not a line: nextInt consumes a number but normally leaves the line ending behind. A following nextLine can therefore return an empty remainder rather than the next line you meant to read.

Pick a format and explain it

Tell users which values belong on which lines. For simple forms, reading whole lines and parsing selected fields later is often easier to explain than mixing methods. We will do that in the final project. For a numeric token exercise, nextInt is convenient when the supplied input is valid.

Check hasNextLine before reading optional lines. EOF means the supplied input has ended; it is not an empty String line. Calling nextLine after EOF fails with an exception, whereas a real blank line can legitimately return an empty string. Keep one reader for System.in rather than creating several competing readers.

Read a name line and a duration token Java
import java.util.Scanner;

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

        System.out.println(name + ": " + minutes + " min");
    }
}
Check your prediction
Ada Lovelace: 25 min

The name includes its internal space because nextLine reads a whole line. Change the two supplied lines and rerun; editing the input box does not require editing the code.

The token-to-line boundary Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int minutes = input.nextInt();
        String remainder = input.nextLine();
        String topic = input.nextLine();

        System.out.println(minutes);
        System.out.println("[" + remainder + "]");
        System.out.println(topic);
    }
}
Check your prediction
25
[]
Java basics

After nextInt, the first nextLine consumes what remains of that numeric line. Here it is empty. The second nextLine reads Java basics. Do not add random extra reads without understanding which input they consume.

Read until the supplied input ends Java
import java.util.Scanner;

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

        while (input.hasNextLine()) {
            String line = input.nextLine();
            count++;
            System.out.println(count + ": " + line);
        }
    }
}
Check your prediction
1: Java
2: Loops

Each successful iteration consumes one line, which moves the reader toward EOF. Empty input runs zero iterations. This is a termination argument based on consuming bounded supplied input.

Your turn

Exercise

Read and report two lines

The input contains a topic on the first line and a learner name on the second. Read both as whole lines and print Ada studies Java basics for the supplied input. Assume exactly two valid lines in this exercise; explain that precondition.

Your workspace Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // Read two lines and build one message.
    }
}
Hint 1: the idea

Line order is part of the input format. Both fields may contain spaces.

Hint 2: a first step

Read topic first and name second. Avoid next(), which would read only one whitespace-separated token.

Show one solution
import java.util.Scanner;

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

        System.out.println(name + " studies " + topic);
    }
}
Ada studies Java basics

Change it and explain

Run with an empty first line, then with the second line missing. Explain why those are different situations. For an optional second line, guard the read with hasNextLine; deciding what message to display is a separate product choice.

Our browser examples are like piping input into a local Java program. A local terminal can provide input interactively, but do not expect the browser widget to behave like that terminal. Later optional download instructions will explain both modes without changing the methods that process the data.

Was this article helpful?

Your response is saved on this device.