Home  >  Article  >  Java  >  Why am I getting an InputMismatchException when reading double values from the console?

Why am I getting an InputMismatchException when reading double values from the console?

Barbara Streisand
Barbara StreisandOriginal
2024-11-07 11:46:02646browse

Why am I getting an InputMismatchException when reading double values from the console?

Why am I encountering InputMismatchException while trying to input double values?

In the provided code, you are experiencing an InputMismatchException because the nextDouble() method is not correctly handling decimal input.

Explanation:

In your code, you have the following line:

num = reader.nextDouble();

This line attempts to read a double value from the standard input using the nextDouble() method of the Scanner class. However, when you enter a double value with a decimal point (e.g., 1.2), it is not interpreted correctly.

Solution:

To fix this issue, you should modify your code to handle decimal input by changing the input delimiter to allow decimal separators. Instead of using the default delimiter (whitespace), you can use , (comma) as the new delimiter, allowing the user to input decimal values like 1,2.

To do this, use the useDelimiter method on the Scanner object before reading the input. Here's the modified code:

Scanner reader = new Scanner(System.in).useDelimiter(",");

By making this change, the nextDouble() method will correctly interpret the decimal input, and you should no longer encounter the InputMismatchException.

The above is the detailed content of Why am I getting an InputMismatchException when reading double values from the console?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn