(InputMismatchException) The previous program works well as long as the user enters an integer. Otherwise, you may get another kind of exception. For instance, if you use nextInt() of Scanner, you could have an InputMismatchException. Modify it to prevent users entering anything other than an integer.
时间: 2024-03-07 12:49:02 浏览: 91
To prevent users from entering anything other than an integer, you can use a loop to keep asking for input until the user enters a valid integer. Here's an example code:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = 0;
boolean validInput = false;
while(!validInput) {
System.out.print("Enter an integer: ");
try {
num = scanner.nextInt();
validInput = true;
} catch (Exception e) {
System.out.println("Invalid input. Please enter an integer.");
scanner.nextLine(); // consume the invalid input
}
}
System.out.println("You entered: " + num);
}
}
```
In this code, we use a `while` loop to keep asking for input until the user enters a valid integer. Inside the loop, we use a `try-catch` block to catch any exceptions that occur when the user enters invalid input. If an exception occurs, we print an error message and consume the invalid input using `scanner.nextLine()`. This allows us to clear the input buffer and ask the user for input again. If the input is valid, we set the `validInput` flag to `true` and exit the loop. Finally, we print the valid input.
阅读全文