java - 实例化数组但不断出现 IndexOutOfBounds 异常

标签 java arrays

我正在尝试统计一个计数数组,以跟上一组 50 个选择,其中每个选择有三个选项。根据我的导师的说法,计数数组应该有 150 个元素 (3 x 50 = 150)。但我在第 55 行不断收到 IndexOutofBounds 异常 (index = thisChoice.get(i))。我认为它一定与我如何(或在哪里?)实例化我的计数数组有关

line 50: int[] count = new int[students.get(0).getChoices().size()*3]

因为其余的代码来 self 的导师,并且可能是正确的。关于什么可能会使其超出范围有什么想法吗?

public class P1Driver {

public static void main(String[] args) throws IOException{

    ArrayList<Students> students = new ArrayList<Students>();
    ArrayList<String> choices = new ArrayList<String>();
    Scanner scan1 = new Scanner(new File("Choices.txt"));
    Scanner scan2 = new Scanner(new File("EitherOr.csv"));

    // Scan the first file.
    int choicesIndex = 0;
    while(scan1.hasNextLine()){
        String line = scan1.nextLine();
        choices.add(line);
        choicesIndex++;
    }
    scan1.close();

    // Scan the second file.
    int studentIndex = 0;
    while(scan2.hasNextLine()){
        String line = scan2.nextLine();
        String [] splits = line.split(","); 

        students.add(new Students(splits[0]));

        for(int i = 1; i < splits.length; i++){
            students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
        }
        studentIndex++;
    }
    scan2.close();

    // Instantiate and add to the count array.
    int index, countIndex;
    ArrayList<Integer> thisChoice;
    int[] count = new int[students.get(0).getChoices().size()*3];
    for(int i = 0; i < students.size(); i++){
        countIndex = 1;
        thisChoice = students.get(i).getChoices();
        for(int j = 0; j < thisChoice.size(); j++){
            index = thisChoice.get(i);
            count[countIndex + index] = count[countIndex + index] + 1;
            countIndex+=3;
        }
    }

    // Display data.
    countIndex = 1;
    for(int i = 0; i < choices.size(); i+=2){
        System.out.println(choices.get(i) + count[countIndex] + choices.get(i+1) + count[countIndex+1] + " Invalid: " + count[countIndex-1]);
        countIndex+=3;
    }

最佳答案

HI 请检查第二个嵌套循环,它应该是 j 而不是 i 。 而且您还没有在该循环中使用 int j

 for (int i = 0; i < students.size(); i++) {
        countIndex = 1;
        thisChoice = students.get(i).getChoices();
        for (int j = 0; j < thisChoice.size(); j++) {
            index = thisChoice.get(j);
            count[countIndex + index] = count[countIndex + index] + 1;
            countIndex += 3;
        }
    }

关于java - 实例化数组但不断出现 IndexOutOfBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46167443/

相关文章:

java - 如何通过Java编码证明 '&&'和 '||'的优先级?

java - Android MediaRecorder/Player无法录制或无法播放

java - 如何使用 Spring Boot 在 mysql 中保存图像?我怎样才能取回它?我在注册时收到 400 错误

javascript - 如何通过单一方法从不同索引的数组中删除元素?

java - 如何使用反射来检查使用不同类加载器加载的类的非静态字段?

java - 模块之间的实体和DTO通信

c++ - 无法将偏移索引计算到 3D 数组中

c - 找到数组中可能的最大总和的最佳答案是什么

javascript - 使用 React 获取数组中的下一个项目

javascript - 将响应结果存储在变量中