When we use specific types of functions such as Scancer.haxNextInt() to obtain input values, we may encounter errors that do not match the type, and we usually catch the error. But after that, we still can't continue to input, but report an error in a consistent loop
use try/catch
public static void test1(){
Scanner scanner = new Scanner(System.in);
int i = 0;
while (i<3){
try {
int a = scanner.nextInt();
System.out.println(a);
}catch (Exception e) {
e.printStackTrace();
}finally {
i++;
}
}
scanner.close();
}
Will generate the following error
or use if/else
public static void test2(){
Scanner scanner = new Scanner(System.in);
int i = 0;
while (i<3){
if(scanner.hasNextInt()) {
int a = scanner.nextInt();
System.out.println(a);
}else{
System.out.println("输入不合法");
}
i++;
}
scanner.close();
}
Will generate the following error
Solution
The reason for the error is that the value in the Scanner buffer has not been taken away, so the next cycle will still be the last incorrect value
So we can take it away through next() or nextLine()
public static void test3(){
Scanner scanner = new Scanner(System.in);
int i = 0;
while (i<3){
try {
int a = scanner.nextInt();
System.out.println(a);
}catch (Exception e) {
System.out.println(scanner.nextLine()+"不合法");
e.printStackTrace();
}finally {
i++;
}
}
scanner.close();
}
The problem is solved, as shown below
Alternatively, we can reassign the scanr and clear the buffer
public static void test4(){
Scanner scanner = new Scanner(System.in);
int i = 0;
while (i<3){
try {
int a = scanner.nextInt();
System.out.println(a);
}catch (Exception e) {
scanner=new Scanner(System.in);
e.printStackTrace();
}finally {
i++;
}
}
scanner.close();
}
The problem is solved as follows