问题
I want to catch any input that is not an Int and prompt for a valid input 3 times. After 3 times, the program will move on and ask for another rating. I can't seem to have the try/catch block repeat or even catch the InputMismatchException. Any suggestions?
do {
//prompt for rating
try {
System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): ");
//capture
rating = response.nextInt();
} catch (InputMismatchException err) {
System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: ");
rating = response.nextInt();
} //end catch
} while (rating >= 0);
回答1:
You could either do it in a loop:
int count = 0;
do {
//prompt for rating
try {
System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): ");
//capture
rating = response.nextInt();
} catch (InputMismatchException err) {
System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: ");
count++;
} //end catch
} while (rating >= 0 && count < 3);
Or use a nested try/ catch:
do {
//prompt for rating
try {
System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): ");
//capture
rating = response.nextInt();
} catch (InputMismatchException err) {
System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: ");
try {
System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): ");
//capture
rating = response.nextInt();
} catch (InputMismatchException err) {
System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: ");
rating = response.nextInt();
} //end catch
} //end catch
} while (rating >= 0);
Personally I would prefer the first method.
I tried this code and it ran without any Exception:
public class Main {
public static void main(String[] args) throws IOException {
int count = 0;
int rating = 0;
do {
Scanner response = new Scanner(System.in);
//prompt for rating
try {
System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): ");
//capture
rating = response.nextInt();
} catch (InputMismatchException err) {
System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: ");
} finally {
count++;
System.out.println("Rating-->" + rating);
}
} while (rating >= 0 && count < 3);
}
}
来源:https://stackoverflow.com/questions/29813230/using-inputmismatchexception-try-catch-block