如何修复InputMismatchException

时间:2012-04-07 23:15:56

标签: java error-handling io

所以我有这段代码:

protected void giveNr(Scanner sc) {
    //variable to keep the input
    int input = 0;
    do {
      System.out.println("Please give a number between: " + MIN + " and " + MAX);
      //get the input
      input = sc.nextInt();
    } while(input < MIN || input > MAX);
}

如果人类输入的不是整数,比如字母或字符串,程序会崩溃并给出错误InputMismatchException。如何修复它,以便在输入错误类型的输入时,再次询问人类输入(并且程序不会崩溃?)

1 个答案:

答案 0 :(得分:2)

你可以抓住InputMismatchException,打印一条错误消息,告诉用户出了什么问题,然后再次循环:

int input = 0;
do {
    System.out.println("Please give a number between: " + MIN + " and " + MAX);
    try {
        input = sc.nextInt();
    }
    catch (InputMismatchException e) {
        System.out.println("That was not a number.  Please try again.");
        input = MIN - 1; // guarantee we go around the loop again
    }
while (input < MIN || input > MAX)