Skip to content

Scanner & Standard Input

The Course
•
15 min study

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");
    }
}
Ada Lovelace 25
Check your prediction
Text
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);
    }
}
25 Java basics
Check your prediction
Text
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);
        }
    }
}
Java Loops
Check your prediction
Text
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.

Match a reading method to the input contract

A token read and a line read stop at different boundaries. nextInt reads a numeric token, while nextLine consumes the rest of the current line. Mixing them without accounting for the leftover newline can produce an empty first line. The earlier example shows that behavior deliberately; it is not evidence that the next line of input disappeared.

For this course's line-oriented formats, reading a full line and parsing it gives you one clear record boundary. You can preserve the original line for an error message and decide whether blank input is skipped or rejected. Do not use a numeric token reader when the format requires one quantity per whole line and friendly recovery from malformed text.

Input in the browser is supplied before Run. The buffer ends at EOF; a Java program cannot wait for another chat response halfway through execution. Start with a short known buffer and trace exactly which read consumes each part.

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.
    }
}
Java basics Ada
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
Java
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);
    }
}
Text
Ada studies Java basics

Two nextLine() calls read the two lines in order, and each keeps its spaces. next() would have stopped at the space and read only Java.

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.