无法从 InputMismatchException 中恢复

Not able to recover from InputMismatchException

我正在学习 java try catch 并使用以下代码

public static void main(String[] args) {

    Scanner in = null;
    int i = 0;

    try {
        in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        i = in.nextInt();
    } catch (InputMismatchException ex) {
        System.out.printf("%nPlease enter a number: %d", in.nextInt());
    } finally {
        if (in != null) {
            System.out.println();
            System.out.println("Finally block !!!");
            in.close();
        }
    }

}

运行 那些程序并输入带有堆栈跟踪的字符串 return java 并退出(不要求用户输入正确的数字)。 如果我删除 catch 块内的 in.nextInt(),我看不到堆栈跟踪但也不会要求用户输入 - 立即退出。

我无法弄清楚我的代码有什么问题

try catch finally 块的工作方式如下:

  1. 执行try块中的代码,在本例中,让用户输入一些内容。
  2. 如果抛出catch中指定的异常,则catch块中的代码只执行一次.
  3. 执行finally块中的代码。

如果你想等到用户输入 int,你应该使用 forwhile 循环:

Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int i;

while (true) {
    try {
        i = Integer.parseInt(in.nextLine());
        System.out.println("Your input is " + i);
        break;
    } catch (NumberFormatException exception) {
        System.out.println("Please enter a number:");
    }
}