你既可以做一个循环:
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);
或者使用嵌套的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);
个人而言,我更喜欢第一种方法。
我想这个代码,并运行,没有任何例外:
公共类主要{
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'之外的'做,while'循环,初始化为'0',在'catch'块中,递增'counter'并将'rating'设置为'-2'。 – MadProgrammer