你既可以做一個循環:
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