运行Java代码持续出现Index 1 out of bounds for length 1错误如何解决
问题根源及修复方案
报错原因
- 硬编码使用3个空格分割州名和人口:文本中每行列之间的空格数量不固定,部分行的分隔空格不足3个或者多于3个,调用
split(" ")后得到的trim2数组长度不足2,访问trim2[1]时触发数组索引越界 - 未做行格式校验:如果读取到空行、缺省字段的异常行,直接访问
trim[1]也会触发越界 - 累加逻辑存在错误:
map.put行的嵌套getOrDefault逻辑冗余且无法正确实现同州人口累加
修复后的代码
public static void main(String[] args) throws FileNotFoundException { Map<String, Integer> sort = storeText(); System.out.println("State: \t\t Population:"); for (Map.Entry<String, Integer> entry : sort.entrySet()) { System.out.printf("%-20s %d%n", entry.getKey(), entry.getValue()); } } public static Map<String, Integer> storeText() throws FileNotFoundException { Map<String, Integer> map = new HashMap<>(); FileInputStream file = new FileInputStream("Assignment1CData.txt"); Scanner input = new Scanner(file); while (input.hasNextLine()) { String line = input.nextLine().trim(); // 跳过空行 if (line.isEmpty()) continue; String[] trim = line.split(","); // 校验逗号分割后的字段数量 if (trim.length < 2) continue; // 用正则匹配任意数量空白字符分割,替换原硬编码3空格分割 String[] trim2 = trim[1].split("\\s+"); // 校验分割后的州名、人口字段数量 if (trim2.length < 2) continue; String state = trim2[0].replace(" ", ""); Integer totalPopulation = Integer.parseInt(trim2[1]); // 修复累加逻辑 map.put(state, map.getOrDefault(state, 0) + totalPopulation); } input.close(); return map; }
修改点说明
- 新增空行、异常行校验逻辑,避免非法行触发越界
- 用
split("\\s+")匹配任意数量的空白字符(空格、制表符都可识别),解决空格数量不固定的分割问题 - 修复人口累加逻辑,直接使用
map.getOrDefault(state, 0) + totalPopulation即可实现同州人口累计 - 新增
Scanner资源关闭逻辑,避免资源泄露
内容的提问来源于stack exchange,提问作者tip_yip
相关产品推荐
相关产品推荐

