标签:loops exception-handling java
这个问题已经在这里有了答案: > How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner 5个
> How to use Scanner to accept only valid int as input 6个
我正在尝试在程序中添加catch块以处理输入不匹配异常.我设置了第一个在do while循环中工作的程序,以便为用户提供纠正问题的机会.
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仅是数字”的无限循环.
我如何使它正常工作?
解决方法:
请注意,当扫描程序引发InputMismatchException时,扫描程序将不会传递导致异常的令牌,以便可以通过其他方法检索或跳过该令牌.
为了避免““客户ID仅是数字”的无限循环.”,您需要调用input.next();.在catch语句中,以便可以在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
标签:loops,exception-handling,java 来源: https://codeday.me/bug/20191122/2060049.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。