gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:16:09 27 4
gpt4 key购买 nike

我正在尝试统计一个计数数组,以跟上一组 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com