在 java.lang.ArrayIndexOutOfBoundsException "main"线程中获取异常:索引 12 超出边界长度 12 at voteR.VoteR.main(VoteR.j


public static void main(String[] args) {
BufferedReader bf = null;
BufferedWriter bw = null;

try {
FileReader fr = new FileReader("File.txt");
FileWriter fw = new FileWriter("Output.txt");
bf = new BufferedReader(fr);
bw = new BufferedWriter(fw);
//Skip the first line
bf.readLine(); 
String line;
List<String> finalCheck = new ArrayList<String>();
//Read the file line by line and add the first number of each line (as a String) to the finalCheck List
while((line = bf.readLine()) != null){
String [] idArray = line.split(",");
String idCheck = idArray[0];
finalCheck.add(idCheck);

}

//Checking for any duplicates within the ID's and displaying them on
int i = 0;
int j = 0;
for (i = 0; i <= finalCheck.size(); i++) {
for (j = i + 1; j <= finalCheck.size(); j++) {
String [] array = new String[finalCheck.size()];
finalCheck.toArray(array);
if(array[i].equals(array[j])) { //This is Line 43
fw.write("Duplicate at line: " + array[i]);
}
}
}

} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Cannot read the file");
} finally {
try {
bf.close();
bw.flush();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}

我一直收到标题中显示的错误消息,我不知道如何修复它。你知道是什么问题导致了这个问题吗?我在代码中添加了一个注释,以显示第43行的确切位置,但如果需要任何其他信息,请告诉我,我将非常乐意添加它。

j <= finalCheck.size()应为j < finalCheck.size()

对于大小为x的数组,在Java中,最后一个索引是x - 1,因为Java中的数组从索引0开始。

相关内容

最新更新