为什么控件直接进入catch块而不进入此SSCCE中的try块?

时间:2016-03-06 02:26:49

标签: java exception-handling

在下面的SSCCE中,为什么catch块一次又一次地执行,导致无限循环?

当我运行此程序并提示输入整数时,我输入a

我认为会发生的是InputMismatchException会在try块内的第一行抛出,然后控件将转到catch块,它将打印``一次,然后进入while(true)循环的下一次迭代,它应该再次进入try块并且应该提示我输入整数。

但是一旦它进入while(true)循环,似乎已经开始无休止地进入catch块,因为如果它进入try块,它会促使我再次输入一个整数。 / p>

哪里,哪个是错误?

import java.util.InputMismatchException;
import java.util.Scanner;


public class WhyThisInfiniteLoop {

    public static void main (String [] args) {
        Scanner reader = new Scanner(System.in); 
        int i = 0; 
        System.out.println("Please enter an integer: ");

        while(true){
          try{
             i = reader.nextInt();
             break;  
          }catch(InputMismatchException ex){
             System.out.println("You did not enter an int. Please enter an integer:");
          }
        }

        System.out.println("Input of type int: " + i);
    }

}

输出

Please enter an integer:
a
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not ...
...
...

1 个答案:

答案 0 :(得分:1)

因为您没有在int块中读取不是catch的内容(令牌)。尝试像

这样的东西
try {
    i = reader.nextInt();
    break;  
} catch (InputMismatchException ex) {
    System.out.printf("%s is not an int. Please enter an integer:", reader.next());
}

调用reader.next()(将使用令牌)就足够了。

按原样,您的ScannernextInt会导致错误,即没有int。然后循环尝试读取int(以及失败)。