Scanner double value - InputMismatchException
Question:
When using Scanner to read a double value in Java, why does it throw an InputMismatchException after the correct input is provided?
Cause:
The exception occurs when the input does not match the expected data type, usually due to a locale mismatch.
Solution:
To resolve the issue, specify the Locale when creating the Scanner object:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
Explanation:
Each locale has its own set of decimal and thousand separators. For example, in the US locale, the decimal separator is a period ('.') while in many European locales, it's a comma (,).
When creating the Scanner object without specifying a locale, Java uses the default system locale. If the default locale uses a comma as the decimal separator and the input is entered with a period, the Scanner attempts to read the input as an integer, resulting in an InputMismatchException.
By specifying the US locale, we ensure that the Scanner expects a period as the decimal separator and correctly reads the input as a double value.
The above is the detailed content of Why Does My Java Scanner Throw an InputMismatchException After Correct Double Input?. For more information, please follow other related articles on the PHP Chinese website!