[Error reporting] Scancer's InputMismatchException infinite loop error reporting

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
image.png

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

image.png

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

image.png

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
image.png

Guess you like

Origin blog.csdn.net/weixin_50799082/article/details/129629371