使用 InputMismatchException try/catch 块 [英] Using InputMismatchException try/catch block
本文介绍了使用 InputMismatchException try/catch 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想捕获任何不是 Int 的输入并提示输入有效输入 3 次.3 次后,程序将继续并要求再次评分.我似乎无法重复 try/catch 块,甚至无法捕获 InputMismatchException.有什么建议吗?
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);
推荐答案
你可以循环执行:
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:
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:
公共类 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);
}
}
这篇关于使用 InputMismatchException try/catch 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文