You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中第一个Scanner正常工作第二个抛出InputMismatchException如何解决

问题原因

你当前的代码只对第一个整数n1做了非法输入校验,第二个整数n2读取前没有做任何输入合法性判断:

  • 你在读取n1前的while (!scanner.hasNextInt())逻辑只会把第一个整数之前的非int类型非法输入全部丢弃,保证n1可以正常读取
  • 读取完n1后直接调用scanner.nextInt()读取n2,如果此时输入流中接下来的内容不是int类型(比如输入了字符串、符号等非数字内容),就会直接抛出InputMismatchException
  • 另外scanner.nextInt()只会读取数字内容,不会消费数字后的换行符、空白符之外的非法内容,非法内容会一直残留在输入流中,后续读取会反复报错
解决方法

对两个整数的输入都增加合法性校验,每次读取int前都判断输入流中是否有合法int值,非法内容直接清空并提示重新输入。
修改后的参考代码如下:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while(true) {
        System.out.println("Enter two integers:");
        // 校验第一个整数n1
        while (!scanner.hasNextInt()) {
            System.out.println("输入不是合法整数,请重新输入两个整数:");
            scanner.next(); // 丢弃非法输入
        }
        int n1 = scanner.nextInt();
        // 新增第二个整数n2的校验
        while (!scanner.hasNextInt()) {
            System.out.println("第二个输入不是合法整数,请重新输入第二个整数:");
            scanner.next(); // 丢弃非法输入
        }
        int n2 = scanner.nextInt();
        // 后续业务逻辑
        System.out.println("输入的两个整数为:" + n1 + "、" + n2);
        System.out.println();
    }
}

如果需要更稳妥的处理逻辑,避免输入流残留内容导致的异常,也可以选择每次读取一整行输入,再拆分校验是否为两个合法整数:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while(true) {
        System.out.println("Enter two integers:");
        String line = scanner.nextLine();
        String[] parts = line.trim().split("\\s+");
        if (parts.length != 2) {
            System.out.println("输入格式错误,请输入两个整数,用空格分隔");
            continue;
        }
        try {
            int n1 = Integer.parseInt(parts[0]);
            int n2 = Integer.parseInt(parts[1]);
            // 后续业务逻辑
            System.out.println("输入的两个整数为:" + n1 + "、" + n2);
            System.out.println();
        } catch (NumberFormatException e) {
            System.out.println("输入包含非整数内容,请重新输入");
        }
    }
}

内容的提问来源于stack exchange,提问作者Dan Perez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:54:06