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);
}
}
counter
of some kind outside of thedo-while
loop, intiialised to0
, in thecatch
block, increment thecounter
and set therating
to-2
. – MadProgrammer