Java try catch异常未按预期运行:InputMismatchException不生效问题
问题原因
- 第一个问题:你调用的是
Scanner.next()方法,该方法的返回值固定为String类型,无论输入的是数字、字母还是符号,只要是连续非空白字符都会被转为字符串返回,不会触发InputMismatchException。只有调用nextInt()、nextDouble()这类指定返回类型的API时,输入内容和期望类型不匹配才会抛出该异常。 - 第二个问题:判断非法选项的逻辑存在错误,
!answer.equals(choices)中choices是字符串数组,单个String永远不可能和数组相等,所以只要输入内容不是a/b/c,不管是数字还是其他字母,都会触发InvalidLetterException。
修复方案
- 先通过
Scanner.hasNextInt()判断用户输入是否为整数,如果是直接抛出对应提示,否则再读取输入做选项校验 - 把非法选项的判断逻辑改为校验输入是否在
choices数组范围内 - 可以把校验逻辑嵌入单题循环中,出错后直接重答当前题,无需从头开始答题
修复后参考代码
import java.util.Scanner; import java.util.InputMismatchException; // 你自定义的异常类,这里补个示例方便运行 class InvalidLetterException extends Exception{ public InvalidLetterException(){ super("请输入有效的选项:a/b/c"); } } public class Quiz { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String questions[] = {"What is the color of the sky? ", "What is 1 + 1? ", "What is the capital of the Philippines? ", "Who is the current president of the Philippines? ", "What is the capital of Japan? ", "What is 2 + 3? ", "What is 9 + 1?", "What is the capital of the United States? ", "What is 10 + 10? ", "How many hand fingers do humans have? "}; String choices[] = {"a","b","c"}; int x = 0; while(x<=9) { System.out.println("No." + (x+1) + "." + questions[x]); try { // 先判断是否输入了整数 if(scan.hasNextInt()){ // 读取这个整数避免残留 scan.nextInt(); throw new InputMismatchException(); } String answer = scan.next().trim(); // 清空缓冲区换行符 scan.nextLine(); if(answer.equals(choices[0]) || answer.equals(choices[1]) || answer.equals(choices[2])){ // 选项合法,进入下一题 x++; }else{ throw new InvalidLetterException(); } } catch(InvalidLetterException e) { System.out.println(e.getMessage()); System.out.println("\n你可以重新输入当前题的答案\n"); } catch (InputMismatchException i) { System.out.println("请不要输入数字,请输入a/b/c选项"); System.out.println("\n你可以重新输入当前题的答案\n"); } } System.out.println("所有题目回答完成"); scan.close(); } }
内容的提问来源于stack exchange,提问作者Pablo Job
相关产品推荐
相关产品推荐

