Java:为什么循环中的try-catch块只执行一次?

下面的程序只是从控制台读取整数并将其打印回来 . 当一个人输入非int(如char或String)时,Scanner会抛出异常 . 我试图在'try-catch'块中处理异常并继续阅读下一个输入 . 在从控制台输入第一个非int之后,程序将进入无限循环 . 有人可以帮忙吗?

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");
        }               
    }
}

回答(3)

2 years ago

当扫描程序无法读取整数时,它不会清除输入缓冲区 . 因此,假设输入缓冲区包含“abc”,因为这就是您输入的内容 . 对“nextInt”的调用将失败,但缓冲区仍将包含“abc” . 所以在循环的下一次传递中,“nextInt”将再次失败!

在异常处理程序中调用sc.next()可以通过从缓冲区中删除不正确的标记来解决问题 .

2 years ago

使用字符串:

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");
    }
}
}

2 years ago

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其他方式

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");
        }               
    }