我正在尝试将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只是数字”。
如何正常运作?
答案 0 :(得分:2)
请注意When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
为避免“无限循环”,客户ID仅为数字“。”,您需要在catch语句中调用input.next();
以便可以重新输入数字控制台
这
语句
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
答案 1 :(得分:1)
发生的事情是你捕获了不匹配,但是仍然需要清除数字“错误的输入”并且应该调用.next()。编辑:因为您还要求它/或等于每次
时大于或等于1boolean valid = false;
while(!valid) {
try {
custID = input.nextInt();
if(custID >= 1) //we won't hit this step if not valid, but then we check to see if positive
valid = true; //yay, both an int, and a positive one too!
}
catch (InputMismatchException e) {
System.out.println("Customer IDs are numbers only");
input.next(); //clear the input
}
}
//code once we have an actual int
答案 2 :(得分:0)
为什么不使用扫描仪对象来使用Scanner.readNextInt()
来阅读它?
答案 3 :(得分:0)
我明白了,这是你正在寻找的解决方案:
public class InputTypeMisMatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int custID=0;
System.out.println("Please enter a number");
while (!input.hasNextInt()) {
System.out.println("Please enter a number");
input.next();
}
custID = input.nextInt();
}
}