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

Java do while循环接收非法输入后无法识别合法输入问题排查

问题根因定位
  • 核心错误:Scanner file 实例初始化放在了do-while循环外部。第一次进入循环读取完整份list.csv文件后,文件指针已经移动到文件末尾,后续再进入do-while循环时,file.hasNextLine() 永远返回false,内层遍历文件的循环完全不会执行,哪怕用户输入合法值也无法完成匹配,boolean标记f永远为false,导致死循环。
  • 次要问题:匹配到符合条件的行后没有终止内层遍历,会无意义读取剩余文件内容,不必要消耗IO性能。
修复方案

有两种优化方向,按需选择即可:

  1. 快速修复:将文件Scanner的初始化逻辑挪到do-while循环内部,每次用户输入后都重新读取文件内容做匹配
  2. 性能优化:程序启动时先一次性读取全部文件内容,将首字符与对应行的映射关系缓存到Map/List中,后续用户输入直接和缓存内容匹配,避免重复读取文件IO
修复后代码示例(快速修复版)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class test {

    public static void selection() throws FileNotFoundException {
        boolean f = false;
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Make booking:");

        do {
            System.out.print("        Select the car number from the car list: ");
            char input = keyboard.next().charAt(0);
            String storeInput = "";
            // 每次循环都重新初始化文件Scanner,重置文件读取指针
            Scanner file = new Scanner(new File("list.csv"));

            while (file.hasNextLine()) {
                storeInput = file.nextLine();
                if (storeInput.charAt(0) == input) {
                    System.out.println(storeInput + " is the booking ");
                    f = true;
                    // 匹配到就跳出内层循环,不用继续读剩下的行
                    break;
                }
            }
            file.close(); // 用完关闭文件流避免资源泄漏
            if (!f) {
                System.out.println("Invalid car selection");
            }
        } while (!f);
        keyboard.close();
    }

    public static void main(String[] args) throws FileNotFoundException {
        selection();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:27:08