一维数组排序程序出现ArrayIndexOutOfBoundsException问题求助
数组索引越界问题分析与修复
问题根源
你碰到的ArrayIndexOutOfBoundsException本质是行号计数和数组索引的逻辑不匹配:
- Java数组索引从0开始,长度为5的数组有效索引是
0~4 - 你的代码里
lineNum初始为0,进入循环后先执行lineNum++,导致第一条记录就用索引1,处理第5条记录时lineNum变成5,直接超出数组的最大索引4,触发异常。 - 哪怕输入条目数4,文件里的5条记录会让循环执行5次,
lineNum最终到5,依然超出长度4的数组(最大索引3),所以同样报错。
修复代码(仅修改数组相关逻辑,其余部分保持不变)
1. 调整readFile方法的行号逻辑
public static void readFile(String pFileName, int numOfEntries) { FileInputStream fileStream = null; InputStreamReader rdr; BufferedReader bufRdr; int lineNum; String line; try { fileStream = new FileInputStream(pFileName); rdr = new InputStreamReader(fileStream); bufRdr = new BufferedReader(rdr); lineNum = 0; // 初始为0,对应数组第一个索引 line = bufRdr.readLine(); Person[] persons = new Person[numOfEntries]; while(line != null && lineNum < numOfEntries) { // 增加判断,避免超出用户输入的条目数 processLine(line, lineNum, persons); // 直接传当前索引给processLine lineNum++; // 处理完当前行再自增索引 line = bufRdr.readLine(); } fileStream.close(); } catch (IOException errorDetails) { if(fileStream != null) { try { fileStream.close(); } catch(IOException ex2) { } } System.out.println("Error in fileProcessing: " + errorDetails.getMessage()); } }
2. 修改processLine方法的数组赋值逻辑
private static void processLine(String csvRow, int index, Person[] persons) { String[] data; data = csvRow.split(","); String name = data[0]; int age = Integer.parseInt(data[1]); double time = Double.parseDouble(data[2]); persons[index] = new Person(name, age, time); // 测试输出调整为对应索引 System.out.print(persons[index].getName() + " "); }
额外说明
- 新增的
lineNum < numOfEntries判断是为了防止用户输入的条目数小于文件实际行数时,代码继续尝试往数组里塞超出长度的数据,进一步避免越界。 - 整个修改只调整了数组索引的使用逻辑,完全保留了你原程序的其他结构和功能。
内容的提问来源于stack exchange,提问作者natadecoco
相关产品推荐
相关产品推荐

