首页 > 解决方案 > 为什么即使我有一个 catch 语句,我仍然会收到 InputMissmatchException

问题描述

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

标签: javaarraysexception-handlingjava.util.scanner

解决方案


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

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

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

推荐阅读