捕获InputMismatchException直到正确为止 [英] Catching an InputMismatchException until it is correct
问题描述
我正在尝试在程序中添加catch块,以处理输入不匹配异常。我将我的第一个设置为在do while循环中工作,以便为用户提供纠正问题的机会。
I am trying add catch blocks to my program to handle input mismatch exceptions. I set up my first one to work inside of a do while loop, to give the user the opportunity to correct the issue.
System.out.print("Enter Customer ID: ");
int custID=0;
do {
try {
custID = input.nextInt();
} catch (InputMismatchException e){
System.out.println("Customer IDs are numbers only");
}
} while (custID<1);
就目前而言,如果我尝试输入字母,则会陷入客户的无限循环ID仅是数字。
As it stands, if I try to enter a letter, it goes into an infinite loop of "Customer IDs are numbers only".
我如何使其正常工作?
推荐答案
请注意,当扫描程序引发InputMismatchException时,扫描程序将不会传递导致异常的令牌,因此可以通过其他方法检索或跳过该令牌。
为避免 客户ID仅是数字的无限循环。 ,您需要致电在catch语句中使用input.next();
使得可以在控制台中重新输入数字
To avoid "infinite loop of "Customer IDs are numbers only".", You need to call input.next();
in the catch statement to to make it possible to re-enter number in Console
从
声明
catch (InputMismatchException e) {
System.out.println("Customer IDs are numbers only");
到
catch (InputMismatchException e) {
System.out.println("Customer IDs are numbers only");
input.next();
}
测试示例:
Enter Customer ID: a
Customer IDs are numbers only
b
Customer IDs are numbers only
c
Customer IDs are numbers only
11
这篇关于捕获InputMismatchException直到正确为止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!