Java Scanner hasNextDouble() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Scanner

Definition

In Java, sc.hasNextDouble() checks whether the next token is formatted as a valid double under the scanner's active locale() without consuming it.

It returns true for whole numbers (10), decimal numbers (3.5 in Locale.US), scientific notation (1.2E3), and NaN or Infinity.

An instance method of java.util.Scanner, available since Java 5 (JDK 1.5). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.hasNextDouble(...).

Locale affects dot vs comma recognition.

Before parsing dot-separated numbers like "4.50", call sc.useLocale(Locale.US); otherwise hasNextDouble() returns false in locales that expect decimal commas (such as German or French).

Syntax

Configure Locale.US when needed, then check hasNextDouble() inside a loop or conditional.

Java
Scanner sc = new Scanner("4.50 free 12.25").useLocale(Locale.US);
if (sc.hasNextDouble()) {
    double price = sc.nextDouble();
}
CallWhat it does
sc.hasNextDouble()Returns true if the next token parses as a double in the scanner locale.
sc.useLocale(Locale.US)Ensures dot-decimal numbers return true everywhere.

hasNextDouble() never throws InputMismatchException. It simply returns false when the next token fails decimal syntax or when input has ended.

Library declarations
Java
// java.util.Scanner
public boolean hasNextDouble()

Parameters

ParameterDescription
NonehasNextDouble() takes no parameters.

Return Value

Return ValueDescription
booleantrue if the token matches the locale's floating-point pattern; false otherwise.
Throws IllegalStateExceptionIf the scanner has been closed.

Compare with Similar Methods

Floating-point lookahead compared:

MethodHow it differs
nextDouble()Reads the checked double value.
hasNextFloat()Checks 32-bit float syntax (same decimal rules).
hasNextBigDecimal()Checks finite exact decimals, rejecting NaN/Infinity.
useLocale(loc)Switches between dot and comma decimal rules.

Java Examples

Example 1 — Sum Valid Prices While Skipping Words Like "free"

Check each token with hasNextDouble() so non-numeric words like "free" are skipped smoothly.

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

public class ScannerHasNextDoublePrices {
    public static void main(String[] args) {
        String receipt = "4.50 free 12.25 discount 3.25";
        double total = 0.0;
        try (Scanner sc = new Scanner(receipt).useLocale(Locale.US)) {
            while (sc.hasNext()) {
                if (sc.hasNextDouble()) {
                    total += sc.nextDouble();
                } else {
                    System.out.println("Skipping word: " + sc.next());
                }
            }
        }
        System.out.println("Total: " + total);
    }
}

How It Works

  1. Guaranteed dot parsing. useLocale(Locale.US) prevents "4.50" from failing on non-English systems.
  2. Non-numbers routed safely. "free" and "discount" return false and are consumed via sc.next().
  3. Clean binary total. 4.50 + 12.25 + 3.25 sums cleanly to 20.0.

Example 2 — Compare hasNextDouble() Under US and German Locales

Test the exact same unconsumed token "3,5" before and after switching locale.

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

public class ScannerHasNextDoubleLocale {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("3,5").useLocale(Locale.US)) {
            System.out.println("US sees 3,5 as double? " + sc.hasNextDouble());
            sc.useLocale(Locale.GERMANY);
            System.out.println("DE sees 3,5 as double? " + sc.hasNextDouble());
            System.out.println("Parsed value: " + sc.nextDouble());
        }
    }
}

How It Works

  1. Failed peek keeps token ready. Returning false under Locale.US leaves "3,5" waiting at the front of the scanner.
  2. Locale switch unlocks it. Switching to Locale.GERMANY flips hasNextDouble() to true on that exact same token.
  3. Standard Java output. Once read by nextDouble(), Java prints the numeric value as 3.5.

Example 3 — Test hasNextDouble() on Exponents, NaN, and Infinity

Compare hasNextDouble() with hasNextBigDecimal() on scientific notation and special values.

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

public class ScannerHasNextDoubleSpecial {
    public static void main(String[] args) {
        String tokens = "1.2E2 NaN Infinity";
        try (Scanner sc = new Scanner(tokens).useLocale(Locale.US)) {
            while (sc.hasNext()) {
                boolean asDbl = sc.hasNextDouble();
                boolean asDec = sc.hasNextBigDecimal();
                System.out.println(sc.next() + " -> double=" + asDbl + ", BigDecimal=" + asDec);
            }
        }
    }
}

How It Works

  1. Exponents pass both. Scientific notation 1.2E2 is accepted by both hasNextDouble() and hasNextBigDecimal().
  2. IEEE specials pass double only. NaN and Infinity are valid doubles, returning true only for hasNextDouble().
  3. Peek twice before advancing. Calling both lookahead checks before sc.next() lets us compare them on identical tokens.

Frequently Asked Questions

Yes. Any valid integer can also be read as a double (10.0), so hasNextDouble() returns true.
The scanner uses the JVM default locale, where some regions use commas (3,5) instead of dots. Call sc.useLocale(Locale.US) for dot decimals.
Yes. Scanner accepts NaN and Infinity as floating-point tokens for nextDouble().
No. It only inspects the next token without consuming it.
No. Floating-point numbers in Scanner are always base 10.

Next: hasNextFloat()

Check whether the next token can be parsed as a float.

hasNextFloat() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful