Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Scanner.nextInt()

Reads the next integer from the input. Related: nextDouble(), next() and hasNextInt().

Available since: Java 5

Syntax

public int nextInt()

Return value

intThe int that was read.

Examples

Numbers separated by spaces and line breaks (here the input is a string; the keyboard works the same):

void main() {
    var scanner = new Scanner("3 4\n5");
    int sum = 0;
    while (scanner.hasNextInt()) {
        sum += scanner.nextInt();
    }
    IO.println(sum);
}

Output:

12

A trap: after nextInt() the line break stays in the input, and nextLine() returns an empty string:

void main() {
    var scanner = new Scanner("30\nAnna\n");
    int age = scanner.nextInt();
    String name = scanner.nextLine();
    IO.println("[" + name + "]");
    name = scanner.nextLine();
    IO.println("[" + name + "]");
}

Output:

[]
[Anna]

Notes

If the next token is not a number, nextInt() throws InputMismatchException; check first with hasNextInt(). To avoid the line break trap, call an extra nextLine() after nextInt(), or read everything with nextLine() and parse it with Integer.parseInt().

nextDouble() depends on the system language: in a German or Russian locale it expects 3,5, not 3.5. Set the format explicitly with scanner.useLocale(Locale.ROOT).

See also

  • Scanner — Reads input piece by piece: whole lines (nextLine) or separate words and numbers.
  • Integer.parseInt() — Converts a string containing an integer to an int.
  • IO.readln() — Prints a prompt and reads a line typed by the user.

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.