Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-11-07 11:46:02
Original
649 people have browsed it

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();
Copy after login

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(",");
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!