The below program simply reads integers from the console and prints it back. When one enters a non-int (like char or String), the Scanner throws an exception. I tried to handle the exception in the 'try-catch' block and move on to read the next input. After the first non-int input from console, the programs runs into infinite loop. Can someone please help?

public class ScannerTest {
    static int i=1;
    static Scanner sc;
    public static void main (String args[]){
        sc = new Scanner(System.in);
        while (i!=0){
            System.out.println("Enter something");
            go();
        }       
    }   
    private static void go(){
        try{
            i = sc.nextInt();
            System.out.println(i);
        }catch (Exception e){
            System.out.println("Wrong input, try again");
        }               
    }
}
有帮助吗?

解决方案

When the scanner fails to read the integer, it does not clear the input buffer. So let's say the input buffer contains "abc" because that's what you entered. The call to "nextInt" will fail, but the buffer will still contain "abc". So on the next pass of the loop, the "nextInt" will fail again!

Calling sc.next() in your exception Handler should correct the problem, by removing the incorrect token from the buffer.

其他提示

use String :

import java.util.Scanner;

public class ScannerTest {

static int i = 1;
static Scanner sc;

public static void main(String args[]) {
    sc = new Scanner(System.in);
    while (i != 0) {
        System.out.println("Enter something");
        go();
    }
}

private static void go() {
    try {
        i = Integer.parseInt(sc.next());
        System.out.println(i);
    } catch (Exception e) {
        System.out.println("Wrong input, try again");
    }
}
}
As  devnull said take the input from user everytime either in loop or in method,just change the loop to ..and it works fine

1)

 while (i!=0){
         sc = new Scanner(System.in);
        System.out.println("Enter something");
        go();

    } 

2 Other Way

private static void go(){
        try{ sc = new Scanner(System.in);
            i = sc.nextInt();
            System.out.println(i);
        }catch (Exception e){
            System.out.println("Wrong input, try again");
        }               
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top