Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Scanner.nextDouble() — read a double value

`Scanner.nextDouble()` reads the next input token as a primitive `double`. The scanner’s locale controls which decimal and grouping separators it recognizes.

Version: Java SE 21

Syntax

public double nextDouble()

// Call on an existing java.util.Scanner instance:
double value = scanner.nextDouble();

Scanner.nextDouble() is a no-argument instance method of java.util.Scanner. The call scanner.nextDouble() skips delimiters before the next token, converts that token to a primitive double, and advances past it on success. The default delimiters are whitespace characters such as spaces and line breaks.

A scanner starts with the default formatting locale (Locale.Category.FORMAT). Its locale affects how it recognizes numbers, including decimal and grouping separators. Use scanner.useLocale(Locale.US) when the input uses a decimal point, as in 12.5.

If the next token does not match the expected format or cannot be converted to a double, the method throws InputMismatchException and leaves the token unread. Exceeding the finite double range does not by itself cause this exception: with Locale.US, the method consumes 1e309 and returns Double.POSITIVE_INFINITY. It throws NoSuchElementException if the input is exhausted and IllegalStateException if the scanner is closed. hasNextDouble() checks the next token without consuming it. If it returns false, use hasNext() to distinguish an invalid token from the end of input. If a token is present, next() can skip it. On interactive input, both checking and reading may wait for more data.

nextDouble() reads a token, not a whole line. If a line break immediately follows the number, a subsequent nextLine() returns an empty string. Closing a scanner also closes its source if that source implements Closeable; closing a scanner built from System.in therefore closes standard input.

Examples

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

public class Main {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner("12.5 -3.25")) {
            scanner.useLocale(Locale.US);
            double first = scanner.nextDouble();
            double second = scanner.nextDouble();
            System.out.println(first);
            System.out.println(second);
        }
    }
}

Result

12.5
-3.25

The program reads from a fixed string, so there is nothing to type. `Locale.US` lets the scanner recognize the decimal point regardless of the default formatting locale. The two `nextDouble()` calls read `12.5` and `-3.25` in order, and the `try` block closes the scanner automatically.

Related lessons

  • Java · Lesson 2 · Basic · Version: 2

Sources