这个问题在这里已有答案:
我正在尝试向我的程序添加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只是数字”。
我该如何正常工作?
请注意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();
,以便可以在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
发生的事情是你捕获不匹配,但仍然需要清除数字“错误的输入”并且应该调用.next()。编辑:因为您还要求每个do / while大于或等于1
boolean 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
为什么不使用扫描仪对象用Scanner.readNextInt()
读取它?
我明白了,这是你正在寻找的解决方案:
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();
}
}