问题描述
我一直在学习JAVA,对代码有一点疑问:
I have been learning JAVA and i have a small doubt about the code :
class apple {
public static void main(String[] args) {
int[] num = new int[3];
Scanner input = new Scanner(System.in);
for (int i = 0; i < num.length; i++) {
try {
num[i] = input.nextInt();
} catch (Exception e) {
System.out
.println("Invalid number..assigning default value 20");
num[i] = 20;
}
}
for (int i = 0; i < num.length; i++) {
System.out.println(num[i]);
}
}
}
我编写了一个处理异常的小程序,如果用户输入不是Int,则抛出异常并分配默认值.如果我将扫描程序语句放入for循环中,则可以正常工作,但是如果我将其置于其赋值之外,则在抛出异常的情况下分配相同的值,即我输入的是char而不是int.但是,如果我输入所有整数,它将在数组中分配正确的值.
I have written small program to handle exception, if user input is not Int throw an exception and assign default value.If i put scanner statement inside for loop, it works fine, but if i take it outside its assign the same value at which exception was thrown i.e i am entering char rather than int.But if i enter all integers it assign correct values in array.
Scanner input = new Scanner(System.in);
我希望你们能理解我的问题.
I hope u guys have understood my question.
推荐答案
Scanner#nextInt
如果无法解析整数,则不会超过输入,因此,如果在失败后继续调用它,它将继续尝试再次解析相同的输入,并抛出InputMismatchException
.
您可以致电 Scanner#next
,忽略它返回的字符串,在您的catch
块中跳过无效的输入:
You can call Scanner#next
, ignoring the string it returns, in your catch
block to skip the invalid input:
try {
num[i] = input.nextInt();
} catch (Exception e) {
System.out
.println("Invalid number..assigning default value 20");
num[i] = 20;
input.next();
}
这篇关于为什么for循环内的Scanner#nextInt不断抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!