【问题标题】:Why am I still getting a InputMissmatchException even though i have a catch statement为什么即使我有一个 catch 语句,我仍然会收到 InputMismatchException
【发布时间】:2019-04-08 16:24:59
【问题描述】:
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 时,我会遇到错误并退出程序。

【问题讨论】:

  • 堆栈跟踪应该指出哪里异常被抛出

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


【解决方案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");
}

【讨论】:

  • 嗨@EquinoxQuasar,如果它可以帮助您解决问题,请将此答案标记为解决方案:)。
【解决方案2】:

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

【讨论】:

  • 感谢您向我解释差异!
猜你喜欢
  • 2021-03-05
  • 2018-04-10
  • 2021-11-13
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
相关资源
最近更新 更多