为什么我仍然收到 InputMismatchException,即使我有一个 catch 语句

Why am I still getting a InputMissmatchException even though i have a catch statement

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 时,我直到出现错误并且程序退出。

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

但这不是导致您出现问题的原因。如果您只想打印错误并继续,那么当您尝试将 String 解析为 Int 而不是输入时出现异常时,您应该将代码切换为 nextInt() instead of next() and parseInt(). Then the exception will be correct and it will be easier to read. (Currently you probably get 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");
}

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

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

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");
  }
}