Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Scanner.nextInt(): read an integer

Read the next token as an `int`, check whether it is valid before reading, and see why a following `nextLine()` can return an empty string.

Version: Java SE 21

Syntax

import java.util.Scanner;

// On an open Scanner instance named scanner:
int value = scanner.nextInt();
int hexValue = scanner.nextInt(16);

In Java SE 21, Scanner.nextInt is an instance method of java.util.Scanner. Calling scanner.nextInt() skips leading delimiters and reads one token as an int. By default, delimiters are whitespace such as spaces and line breaks. The method does not read a whole line.

nextInt() uses the scanner's current default radix (number base), which starts at 10 and can be changed with useRadix. The overload nextInt(int radix) selects a base for that call only. For example, nextInt(16) reads 2a as 42. Bases from 2 through 36 are valid; anything outside that range causes IllegalArgumentException. The scanner's locale can affect accepted number formats, including digit grouping.

hasNextInt() checks the next token without consuming it. For an explicit base, use the matching hasNextInt(radix). A false result can mean either an invalid token or exhausted input. Without the check, reading a token with the wrong format or a value outside the int range throws InputMismatchException. The offending token remains available; call next() to discard it. Exhausted input throws NoSuchElementException, and reading from a closed scanner throws IllegalStateException.

If there are characters left on the current line after reading a number, nextLine() returns them without the line separator. If the line break immediately follows the number, the result is "", and the scanner moves to the start of the next line. If the input ends immediately after the number with no line separator (for example, if the input is just 42), nextLine() throws NoSuchElementException.

The example reads from a string and closes the scanner with try-with-resources. With System.in, checking or reading can block while waiting for input. Closing the scanner also closes System.in, so don't close it while another part of the program still needs that stream.

Examples

import java.util.Locale;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner("42\n2a\n")) {
            scanner.useLocale(Locale.ROOT);
            if (scanner.hasNextInt()) {
                System.out.println(scanner.nextInt());
                System.out.println("[" + scanner.nextLine() + "]");
                System.out.println(scanner.nextInt(16));
            }
        }
    }
}

Result

42
[]
42

The first `42` is read in decimal. `[]` shows the empty remainder of the first line, and the final `42` is the value of the hexadecimal token `2a`.

Related lessons

  • Java · Lesson 2 · Basic · Version: 2

Sources