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

Java如何处理InputMismatchException?输入校验循环代码错误排查

问题分析
  • 循环条件错误:while(bool = false)是赋值操作,恒返回false,循环永远不会执行。同时你在进入循环前就直接调用scan.nextInt(),如果用户首次输入非整数,会直接抛出InputMismatchException,没有任何错误处理逻辑。
  • 执行顺序颠倒:你先执行scan.nextInt()读取输入,再判断输入类型,一旦输入不是整数,nextInt()直接抛出异常,后续的类型判断代码完全不会执行。
  • 错误输入未消费:如果Scanner读取整数失败,输入指针不会自动后移,会一直卡在错误的输入内容上,必须主动调用nextLine()清空缓存的错误输入,否则会进入死循环。
  • 类型判断逻辑错误:hasNextDouble()会匹配整数(整数也属于合法的double范围),同时hasNext()只要有输入就会返回true,二者的判断顺序和逻辑会导致错误提示不准确。
修正后代码
import java.util.Scanner;

public class LoopPrac {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num;
        boolean inputValid = false;

        while (!inputValid) {
            System.out.println("Enter an Integer: ");
            // 先判断输入是否为整数
            if (scan.hasNextInt()) {
                num = scan.nextInt();
                inputValid = true;
                // 消费剩余换行符
                scan.nextLine();
                System.out.println(num);
            } else {
                // 读取错误输入内容用于类型判断
                String wrongInput = scan.nextLine();
                try {
                    // 尝试转换为浮点数判断输入类型
                    Double.parseDouble(wrongInput);
                    System.out.println("Error: Index is Double not Integer.");
                } catch (NumberFormatException e) {
                    System.out.println("Error: Index is String not Integer.");
                }
            }
        }
        scan.close();
    }
}

内容的提问来源于stack exchange,提问作者L. Jacob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:54:03