为什么即使我有catch语句,为什么仍然收到InputMissmatchException

时间:2018-11-05 10:09:21

标签: java arrays exception-handling java.util.scanner

System.out.print("What kind of array do you want to create?\n1. Integer Array\n2. Double Array\n3. String Array\nYour Answer: ");
String input;
int num1 = 0;
try {
    input = s.next();
    num1 = Integer.parseInt(input);
    while (num1 > 3 || num1 < 1) {
        System.out.print("Please enter one of the three available options.\nYour Answer: ");
        input = s.next();
        num1 = Integer.parseInt(input);
    }
} catch (InputMismatchException e) {
    System.out.println("Do not enter a letter/special character");
}

因此,我基本上是在向用户提出一个问题,询问他要创建哪种数组。但是,当我尝试破坏它并放入Char / String时,直到出现错误,程序退出。

2 个答案:

答案 0 :(得分:1)

在while循环内添加try-catch块。否则,异常将在循环之后被捕获,并且当您处理异常(在catch块中)时,您将继续执行流程,而无需要求用户重试。

但这不是导致您出现问题的原因。如果您只想打印错误并继续,则应将代码切换为nextInt(),而不是next()parseInt()。这样,异常将是正确的,并且将更易于阅读。 (当前,当您尝试将String解析为Int而不是输入异常时,您可能会得到NumberFormatException -如果您要那样做,请更改尝试捕获的异常)

int num1 = 0;
try {
    num1 = s.nextInt();
    while (num1 > 3 || num1 < 1) {
        System.out.print("Please enter one of the three available options.\nYour Answer: ");
        num1 = s.nextInt();
    }
} catch (InputMismatchException e) {
    System.out.println("Do not enter a letter/special character");
}

答案 1 :(得分:0)

s.next()String读取Scanner。因此,如果您输入非数字的String,则不会抛出InputMismatchException。相反,当尝试将Integer.parseInt解析为NumberFormatException时,String会抛出int,而您不会捕获该异常。

您可能想尝试这样的事情:

Scanner s = new Scanner (System.in);
System.out.print("What kind of array do you want to create?\n1. Integer Array\n2. Double Array\n3. String Array\nYour Answer: ");
String input;
int num1 = 0;
input = s.next();
try {
  num1 = Integer.parseInt(input);
}
catch (NumberFormatException numEx) {
  System.out.println("Do not enter a letter/special character");
}
while (num1 > 3 || num1 < 1) {
  System.out.print("Please enter one of the three available options.\nYour Answer: ");
  input = s.next();
  try {
    num1 = Integer.parseInt(input);
  }
  catch (NumberFormatException numEx) {
    System.out.println("Do not enter a letter/special character");
  }
}