该程序仍然抛出 InputMismatchException 并退出,即使它已被捕获

The Program still throws an InputMismatchException and exits even though its been caught

我刚刚开始学习 Java,我正在努力处理异常。我正在尝试编写一个快速程序,它接受一些输入并将它们转换为不同的单位。

我正在使用 Scanner 获取输入,我正在尝试防止 InputMisatchException,但尽管在它周围放置了一个 try-catch 块来处理异常,它仍然存在。代码如下。希望你能帮忙!提前致谢。

import java.util.InputMismatchException;

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    //init variables
    String name = "";
    int age = -1;
    int height_in_cm = -1;

    //Init Scanner
    Scanner input = new Scanner(System.in);

    //Get the input from the user and save to the initiated variables above.
    System.out.print("Please enter your name: ");
    name = input.nextLine();
    try{
    System.out.printf("Hey, %s. How old are you?: ", name);
    age = input.nextInt();
    } catch (InputMismatchException e){
        System.out.printf("Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: ", name);
        age = input.nextInt();
    }
    System.out.print("And finally, what is your height in CM?: ");
    height_in_cm = input.nextInt();

    //close the scanner to protect from resource leaks.
    input.close();


  }
}```

您还需要 try-catch

height_in_cm = input.nextInt();

否则你会得到另一个异常!

异常的原因是第一次抛出异常时Scanner(input)没有更新它的指针,所以catch块中的input.nextInt()读取了与input.nextInt() 的 try 块。

要解决此问题,请在读取 int 值之前在 catch 块中添加 input.nextLine()

 try{
        System.out.printf("Hey, %s. How old are you?: ", name);
        age = input.nextInt();
    } catch (InputMismatchException e){
        System.out.printf("Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: ", name);
        input.nextLine();
        age = input.nextInt();
    }

原因是您正在捕获 catch 块中的错误。尝试为它实现一个循环。还要记得使用 input.next(); 清除缓冲区,否则你会遇到 infinite-loop

do
{
    try
    {
        System.out.printf("Hey, %s. How old are you?: ", name);
        age = input.nextInt();
        stop = true;
    } 
    catch (InputMismatchException e)
    {
        System.out.printf("Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: ", name);
        input.next(); // Clearing the buffer. This is important otherwise Infinite Loop will occur
    }
} while( !stop );