Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Scanner.useLocale — set the locale for reading numbers

Set the locale for one scanner so it reads numbers using the conventions of the input, such as a comma as the decimal separator.

Version: Java SE 21

Syntax

public Scanner useLocale(Locale locale)

scanner.useLocale(Locale.GERMANY);

Scanner.useLocale is an instance method of java.util.Scanner. It takes a java.util.Locale object, not a string. It changes only that scanner's locale and returns the same scanner, so you can chain a call to nextDouble(). It does not change the JVM's default locale.

Set the locale before reading a number to match the input's conventions, including decimal and digit-grouping separators. useLocale does not change the token delimiter or format output. Use locale() to inspect the scanner's current locale. A new scanner starts with Locale.getDefault(Locale.Category.FORMAT); reset() goes back to the default FORMAT locale and also restores the default delimiter and radix.

hasNextDouble() checks the next token without consuming it. If nextDouble() cannot read an existing token as a double, it throws InputMismatchException and leaves that token unconsumed. If the input is exhausted, it throws NoSuchElementException; if the scanner is closed, it throws IllegalStateException.

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 12.5")) {
            double german = scanner.useLocale(Locale.GERMANY).nextDouble();
            double us = scanner.useLocale(Locale.US).nextDouble();

            System.out.println(german);
            System.out.println(us);
        }
    }
}

Result

12.5
12.5

The same scanner reads `12,5` with `Locale.GERMANY`, then `12.5` with `Locale.US`. Both forms produce the same `double` value. `println(double)` prints `12.5` with a dot on both lines; it does not use the scanner's locale.

Related lessons

  • Java · Lesson 2 · Basic · Version: 2

Sources