Home >Java >javaTutorial >Scanner Double Value: InputMismatchException - Why Does It Occur and How Can It Be Avoided?
Scanner Double Value Exception: InputMismatchException
Problem Introduction:
When using the Scanner class to read double values from the console, a user may encounter the InputMismatchException. This error occurs when the input does not match the expected data type, in this case, a double.
Questions:
Answers:
1. Why does the exception occur?
The InputMismatchException is thrown because the default locale of the Scanner is not configured to use a period (.) as the decimal separator. By default, many locales use a comma (,) as the decimal separator. However, floating-point numbers in Java are expected to use a period as the decimal separator. When the Scanner tries to read a double value from an input that uses a comma as the decimal separator, it interprets it as an integer, leading to the InputMismatchException.
2. How to circumvent the exception:
To avoid the InputMismatchException, the following steps can be taken:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
The above is the detailed content of Scanner Double Value: InputMismatchException - Why Does It Occur and How Can It Be Avoided?. For more information, please follow other related articles on the PHP Chinese website!