【问题标题】:Getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 12 at voteR.VoteR.main(VoteR.java:43) [duplicate]在线程“main”java.lang.ArrayIndexOutOfBoundsException中获取异常:在voteR.VoteR.main(VoteR.java:43)处索引12超出长度12的范围[重复]
【发布时间】:2022-01-23 04:36:52
【问题描述】:
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 行的确切位置,但如果需要任何其他信息,请告诉我,我将非常乐意添加它。

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    j &lt;= finalCheck.size() 应该是j &lt; finalCheck.size()

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

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 2021-09-27
      • 2021-07-29
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多