Home > Java > javaTutorial > What Causes an InputMismatchException in Java and How to Fix It?

What Causes an InputMismatchException in Java and How to Fix It?

Susan Sarandon
Release: 2024-11-07 21:29:02
Original
1033 people have browsed it

What Causes an InputMismatchException in Java and How to Fix It?

InputMismatchException in Java Code: Troubleshooting Input

When using the Scanner class in Java, unexpected exceptions can arise during input processing. One common error is the InputMismatchException, which occurs when the input entered doesn't match the expected data type.

Consider this code snippet:

public double checkValueWithin(int min, int max) {
    double num;
    Scanner reader = new Scanner(System.in);
    num = reader.nextDouble();                         
    while (num < min || num > max) {                 
        System.out.print("Invalid. Re-enter number: "); 
        num = reader.nextDouble();                         
    }
    return num;
}
Copy after login

and

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++;
    }
}
Copy after login

When testing this code, you encounter an InputMismatchException due to an improper data type being entered. The issue arises when attempting to enter a double value using a dot (.) as the decimal separator.

Solution:

To resolve this problem, use a comma (,), not a dot, to separate the fractional part of the number. For example, instead of entering 1.2, input 1,2. The comma is the default decimal separator for double data types in Java.

By making this simple modification, you can ensure that the code accepts double values correctly and avoids the InputMismatchException.

The above is the detailed content of What Causes an InputMismatchException in Java and How to Fix It?. 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