当你想要输入一串的内容进入数组,或集合当中时,可能会有InputMismatchException异常,当用catch捕捉异常之后,想要继续重新输入时:
while (true){
try{
System.out.println("请输入第"+count+"个数字");
int num= sc.nextInt();
a[count] = num;
count++;
}catch (InputMismatchException e){
System.out.println("输入格式不正确,请重新输入");
}
}
出现结果却是一直无线循环!!
但是如果将while循环撤掉换成for循环,想要再次输入,也会出现InputMismatchException
这是因为scanner输入的字符类型一直存放于Scanner中,所以在下一次输入的时候,还是会宝输入异常错误。
解决方法:
将Scanner中的数据输导出来,用一个String类型的接受,这个样子就可以继续完成下一次的输入啦!
try{
System.out.println("请输入第"+count+"个数字");
int num= sc.nextInt();
a[count] = num;
count++;
}catch (InputMismatchException e){
System.out.println("输入格式不正确,请重新输入");
String x= sc.next();//接受存放于Scanner中的异常数据,让他可以继续接受控制台输入的数据
continue;//跳过此次异常循环
}