Scanner double Value InputMismatchException
Java programmers commonly encounter the InputMismatchException when attempting to scan double values using the nextDouble() method. This exception signals a discrepancy between the expected data format and the actual input provided.
Why it Happens
The InputMismatchException occurs when the input does not conform to the expected numeric format. In the given code snippet, the scanner is not explicitly configured with a locale. This results in it using the system's default locale, which can have different decimal separators (e.g., "," instead of "." in some European countries). When the scanner interprets the input, it expects a comma-separated decimal, but encounters a dot (.) instead.
How to Circumvent the Issue
To resolve this issue, you can explicitly set the scanner's locale to one that uses the expected decimal separator. This ensures that the scanner correctly interprets the input based on the specified locale.
Solution
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
By using Locale.US, the scanner is configured to use a locale that expects a dot "." as the decimal separator. This aligns with the input format you are expecting (5.1) and prevents the InputMismatchException.
The above is the detailed content of Why Does `Scanner.nextDouble()` Throw an `InputMismatchException`, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!