You need to enable JavaScript to run this app. Java中try-catch捕获InputMismatchException实现整数输入校验的返回值异常咨询
优惠活动
大模型
产品
解决方案
定价
更多

Java中try-catch捕获InputMismatchException实现整数输入校验的返回值异常咨询

问题根因
  • 踩了Java基本类型值传递的经典坑
    int是Java的基本数据类型,传参时采用值拷贝机制:把iPercent传入方法时,Java只会复制这个变量当时的数值给方法的形参test。方法内部所有对test的修改,都只作用在这个临时副本上,完全不会触达方法外部的原始iPercent变量。
  • 调用方法时没有接收返回值
    当前的调用代码PromptErrorCheckingPercent(iPercent);没有将方法最终return的结果赋值给外部目标变量。哪怕方法内部正常捕获到了合法输入、执行了return语句,这个返回值也会因为没有被接收直接丢弃,根本不会写入用来存储结果的整数变量。
  • 方法参数设计冗余且误导逻辑
    方法定义里的int test形参没有实际作用:进入循环后第一行逻辑就是test = keyboard.nextInt();,不管传入的test初始值是多少,进来就会被用户输入直接覆盖,这个传参操作完全多余,反而容易让人误以为传入的变量能被方法直接修改。
修正方案
  • 删掉方法里无意义的入参,避免值传递带来的逻辑混淆
  • 方法内部用独立临时变量存储捕获到的合法输入,通过return将值传递出来
  • 调用方法时,直接把返回值赋值给外部要存结果的变量,不要做无接收的空调用

参考实现代码:

// 建议将Scanner定义在类全局作用域,仅初始化一次,避免重复new对象导致输入流阻塞
public static Scanner keyboard = new Scanner(System.in);

public static int PromptErrorCheckingPercent(){
    boolean valid = false;
    int inputValue = 0;
    while (!valid) {
        try {
            inputValue = keyboard.nextInt();
            // 可根据业务补充范围校验,比如百分比值需在0-100区间
            if (inputValue < 0 || inputValue > 100) {
                System.out.println("Invalid Input. Please enter a value between 0 and 100");
                keyboard.nextLine();
                continue;
            }
            valid = true;
        } catch (InputMismatchException e) {
            System.out.println("Invalid Input. Please enter a valid integer");
            keyboard.nextLine();
        }
    }
    return inputValue;
}

修正后的调用逻辑:

System.out.print("Please enter the percent achieved for " + sName + ": %");
// 直接接收方法返回的合法输入,赋值给外部变量
iPercent = PromptErrorCheckingPercent();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 16:15:03