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

如何处理Java的InputMismatchException并搭配自定义异常使用

问题原因
  • 当Scanner的nextInt()方法触发InputMismatchException时,不会主动消费输入缓冲区中不匹配的非法内容,下一次循环再次调用nextInt()时还是会读取同一段非法输入,就会进入无限抛异常的死循环。
  • 原代码的计数逻辑也存在问题:只有猜高/猜低会计数,猜对的那次尝试不会被计入总次数。
解决方法

在InputMismatchException的捕获分支中,调用scan.nextLine()清空输入缓冲区的残留非法内容即可。同时调整计数逻辑,仅合法数字输入计入尝试次数,无效输入不计入次数(如果需要将无效输入也计入次数,可自行在对应catch块中添加count自增逻辑)。

修正后的完整代码
import java.util.*;

// 补充自定义异常定义,避免编译报错
class InputTooLowException extends Exception {
    public InputTooLowException(String msg) {
        super(msg);
    }
}

class InputTooHighException extends Exception {
    public InputTooHighException(String msg) {
        super(msg);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        final int min = 1, max = 50;
        final int random = (int) Math.floor(Math.random() * (max - min + 1) + min);

        boolean status = false;
        int count = 0;

        while (!status) {
            try {
                System.out.println("Guess a number from 1 to 50: ");
                int answer = scan.nextInt();
                count++; // 合法输入才计入尝试次数

                if (answer < random) {
                    throw new InputTooLowException("");
                } else if (answer > random) {
                    throw new InputTooHighException("");
                } else {
                    System.out.println("\nCongratulations! You got it in " + count + " attempt/s");
                    status = true;
                }

            } catch (InputTooLowException e) {
                System.out.println("Too low. Try again.");
                status = false;
            } catch (InputTooHighException e) {
                System.out.println("Too high. Try again.");
                status = false;
            } catch (InputMismatchException e) {
                System.out.println("Invalid Input");
                status = false;
                scan.nextLine(); // 核心修复:清空输入缓冲区的非法内容
            }
        }
        scan.close();
    }
}

内容的提问来源于stack exchange,提问作者I-dont-know-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:24:05