1

所以我有这个代码:

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. 我该如何解决它,以便在输入错误类型的输入时,再次要求人类输入(并且程序不会崩溃?)

4

1 回答 1

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)
于 2012-04-07T23:43:12.030 回答