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; }
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++; } }
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!