异常后继续while循环

dor*_*thy 3 java

我有这段代码。我想回到循环的开头并再次要求用户输入。然而,它总是循环而不停止请求输入。我的代码有什么问题?谢谢

while(true){
    ... 
    try {
        int choice = input.nextInt(); <<---=- this should stop and ask for input, but it always loops without stopping.

    } catch (InputMismatchException e){
        << I want to return to the beginning of loop here >>
    }

}
Run Code Online (Sandbox Code Playgroud)

Dav*_*d K 7

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28int%29

“如果翻译成功,扫描仪就会越过匹配的输入。”

啊,但是如果翻译是什么不是成功的?在这种情况下,扫描仪不会通过任何输入。错误的输入数据仍然作为下一个要扫描的内容,因此循环的下一次迭代将像前一次一样失败——循环将不断尝试一遍又一遍地读取相同的错误输入。

为了防止无限循环,您必须跳过坏数据,以便获得扫描仪可以读取的整数。下面的代码片段通过调用 input.next() 来做到这一点:

    Scanner input = new Scanner(System.in);
    while(true){
        try {
            int choice = input.nextInt();
            System.out.println("Input was " + choice);
        } catch (InputMismatchException e){
            String bad_input = input.next();
            System.out.println("Bad input: " + bad_input);
            continue;
        }
    }
Run Code Online (Sandbox Code Playgroud)