Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Scanner

Reads input piece by piece: whole lines (nextLine) or separate words and numbers.

Available since: Java 5

Syntax

public final class Scanner implements Iterator<String>, Closeable

Examples

Reading a line from the keyboard. In the console (the user typed Oleg):

void main() {
    var scanner = new Scanner(System.in);
    IO.print("Name: ");
    String name = scanner.nextLine();
    IO.println("Hi, " + name);
}

Output:

Name: Oleg
Hi, Oleg

Scanner reads not only the console but also a string or a file — reading every line to the end:

void main() {
    var scanner = new Scanner("first\nsecond\nthird");
    int n = 1;
    while (scanner.hasNextLine()) {
        IO.println(n++ + ": " + scanner.nextLine());
    }
}

Output:

1: first
2: second
3: third

Notes

nextLine() returns the line without the line break. If there are no more lines it throws NoSuchElementException — check hasNextLine(). Create a scanner for System.in once per program and do not close it: closing the scanner closes System.in too.

For simple line input in Java 25, IO.readln() is shorter.

See also

  • Scanner.nextInt() — Reads the next integer from the input. Related: nextDouble(), next() and hasNextInt().
  • IO.readln() — Prints a prompt and reads a line typed by the user.
  • BufferedReader — Reads text line by line with buffering — the classic way to process large files.

Related recipes

In the tutorial

  • Keyboard input — How to read user input in Java: IO.readln, turning input into a number and the Scanner class.

Thanks for reading!

Donate to the site — we work hard for you.