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

如何修复Java中"Exception in thread "main" java.util.InputMismatchException"错误

错误原因

你的代码存在两个核心问题导致该报错:

  1. fragility字段读取逻辑完全错误
    你在case3中读取易碎性的代码为boolean fragility = input.hasNextFloat();:
  • hasNextFloat()是校验类方法,作用仅为判断输入缓冲区下一个内容是否为浮点数,返回布尔值,但不会消费缓冲区的输入内容
  • 你输入false后,hasNextFloat()判断不是浮点数,返回false赋值给fragility,但缓冲区里仍然留着false字符串
  • 后续执行nextInt()读取数量时,读到的是缓冲区残留的false,类型不匹配直接抛出InputMismatchException
  1. Scanner换行符残留问题
    nextInt()、nextBoolean()这类方法只会读取目标类型内容,不会吞掉输入末尾的换行符,后续调用nextLine()会直接读到空字符串,你之前写两次nextLine()就是为了规避这个问题,但写法不规范也容易出问题。

修复方案

1. 修复易碎性读取逻辑

将读取易碎性的代码替换为input.nextBoolean(),专门读取布尔类型输入,同时主动消费换行符。

2. 统一处理换行残留

每次调用nextInt()、nextBoolean()后,主动加一行input.nextLine()吞掉残留的换行符,无需再写两次nextLine()。

3. 删掉重复的数量读取代码

case3中你写了两次quantity = input.nextInt(),会要求用户输入两次数量,保留一次即可。

4. 修复字符串空校验逻辑

你原来判断空的代码name == ""是错误的,Java中字符串内容比较需要用equals()方法,替换为name.isEmpty()或者"".equals(name)。


修复后的case3参考代码

case 3:
    System.out.println("\n\n");
    System.out.println("**************************************************");
    System.out.println("你选择了选项3:插入商品 \n");

    for (int i = 0; i < warehouses.length; i++) {
        System.out.println("索引 " + i + ": " + warehouses[i].name);
    }

    System.out.println("\n 输入要操作的仓库索引:");
    index = input.nextInt();
    input.nextLine(); // 清除nextInt残留的换行符

    if (index < warehouses.length) 
    {
        System.out.println("输入商品名称:");
        name = input.nextLine();
        
        System.out.println("输入商品是否易碎(true/false):");
        boolean fragility = input.nextBoolean();
        input.nextLine(); // 清除nextBoolean残留的换行符
        
        System.out.println("输入商品数量:");
        quantity = input.nextInt();
        input.nextLine(); // 清除nextInt残留的换行符
        
        insertProduct(name, fragility, quantity, index);
    } 
    else 
    {
        System.out.println("无效的仓库索引");
    }
    break;

其余case4、case5按照相同逻辑调整即可:所有nextInt()调用后加input.nextLine()清换行,删除重复的nextLine()调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:54:02