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

Java读取二进制文件二维数组实现州缩写查询的getState方法问题

Java州缩写检索功能getState方法修复方案

原有代码核心问题

  • 冗余调用readStateFile():main方法已经完成二进制文件读取并传入了states数组,方法内重复读取属于无效操作
  • 对二维数组存储结构理解错误:readStateFile()返回的数组应为每行对应一个州的两组数据,即states[i][0]存缩写、states[i][1]存全称,原有代码按列遍历的逻辑完全不符合数据结构
  • 比较逻辑错误:错误使用数组对象和字符串做equals比较,根本无法匹配用户输入的缩写
  • 返回值不符合需求:原有逻辑返回用户输入的缩写,而非要求的匹配后完整州名
  • 缺少异常兼容:未处理用户输入小写缩写、未匹配到有效数据的提示场景
  • 额外隐藏bug:你提到运行正常的readStateFile()实际存在存储错位问题,循环中j = i + 1的写法会导致州全称的存储列索引随i递增,后续遍历根本找不到对应数据

先修正readStateFile方法的存储逻辑

private static String[][] readStateFile() throws IOException {
    // 每行仅存2列数据,不需要开50列浪费空间
    String states[][] = new String[50][2];
    try {
        FileInputStream fstream = new FileInputStream("states copy.bin");
        DataInputStream inputFile = new DataInputStream(fstream);
        // 固定第0列存缩写,第1列存全称
        for (int i = 0; i < 50; i++) {
            states[i][0] = inputFile.readUTF();
            states[i][1] = inputFile.readUTF();
        }
        inputFile.close();
        return states;
    } catch (EOFException e) {
        throw new CancelledSurveyException("Survey Cancelled");
    }
}

修正后的getState方法

private static String getState(String[][] states) throws IOException, CancelledSurveyException {
    Scanner st = new Scanner(System.in);
    // 加循环支持输错后重新输入,不需要用户重启程序
    while (true) {
        System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
        String input = st.next().trim().toUpperCase();
        // 兼容用户输入小写q的情况
        if (input.equals("Q")) {
            throw new CancelledSurveyException("Your survey was cancelled.\nThank you for your time.");
        }
        // 遍历所有州数据匹配缩写
        for (int i = 0; i < states.length; i++) {
            String abbr = states[i][0];
            if (abbr != null && abbr.equals(input)) {
                // 匹配到直接返回对应全称
                return states[i][1];
            }
        }
        // 遍历完未匹配到提示错误
        System.out.println("You've entered invalid state abbrevation, please try again.");
    }
}

可选优化方案

如果数据量更大可以提前把州数据转成HashMap存储,匹配时间复杂度从O(n)降到O(1),性能更好:

// 在main方法读取到states数组后转成Map
Map<String, String> stateMap = new HashMap<>();
for (String[] state : states) {
    stateMap.put(state[0], state[1]);
}
// getState方法直接传入map调用get即可,不需要循环遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:27:03