I'm making a function in Java that needs an integer input My code is this:
我在Java中创建一个需要整数输入的函数我的代码是这样的:
System.out.println("Input the year");
Scanner scan = new Scanner(System.in)
this.error = true
while (this.error = true) {
try {
this.year = scan.nextInt;
this.error = false;
}
catch(Exception e) {
System.out.println("Try again");
this.year = -1;
}
}
But when I execute it, if the user inputs something that's not an integer, it just prints the error message over and over forever, without letting the user input something else. Sorry if this is really obvious (I'm quite new to programming), but do you know why this happens or how can I fix it?
但是当我执行它时,如果用户输入的内容不是整数,它只会一遍又一遍地打印错误消息,而不会让用户输入其他内容。对不起,如果这是非常明显的(我对编程很新),但你知道为什么会这样,或者我该如何解决?
thanks
1 个解决方案
#1
3
You can use hasNextInt()
method
您可以使用hasNextInt()方法
if(scan.hasNextInt()){
//your code
}
See detailed description of hasNextInt() method
请参阅hasNextInt()方法的详细说明
#1
3
You can use hasNextInt()
method
您可以使用hasNextInt()方法
if(scan.hasNextInt()){
//your code
}
See detailed description of hasNextInt() method
请参阅hasNextInt()方法的详细说明