Home >Java >javaTutorial >Why Am I Getting an InputMismatchException When Reading Double Values with Scanner?

Why Am I Getting an InputMismatchException When Reading Double Values with Scanner?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 21:21:02243browse

Why Am I Getting an InputMismatchException When Reading Double Values with Scanner?

Why Does the InputMismatchException Occur While Getting Double Values?

In Java, when using Scanner to read double values, an InputMismatchException can occur if the input does not strictly adhere to the expected decimal format.

Understanding the Issue:

The provided code contains the checkValueWithin and askForMarks methods. checkValueWithin is intended to validate numeric input within a specified range.

The issue arises in the askForMarks method, where user input is expected to be double values in the range of 0 to 30. However, the input might be formatted incorrectly, causing the Scanner to fail while parsing the double value.

Fix:

This issue can be resolved by ensuring that user input is formatted using a comma as the decimal separator instead of a dot. For example, instead of 1.2, enter 1,2. This aligns with the double value representation in Java.

Here's the modified code for askForMarks:

public void askForMarks() {
    double marks[] = new double[student];
    int index = 0;
    Scanner reader = new Scanner(System.in);
    while (index < student) {
        System.out.print("Please enter a mark (0..30): ");
        marks[index] = (double) checkValueWithin(0, 30);
        index++;
    }
}

This modification ensures that double values are entered correctly, preventing the Scanner from encountering an InputMismatchException.

The above is the detailed content of Why Am I Getting an InputMismatchException When Reading Double Values with Scanner?. 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