我尝试计算一个计数数组以跟上一组50个选项,其中每个选项有三个选项。计数数组应该有150个元素,每个我的教师(3 x 50 = 150)。但是我在第55行(index = thisChoice.get(i)
)继续得到IndexOutofBounds异常。我认为它必须与如何(或在哪里?)我在
line 50: int[] count = new int[students.get(0).getChoices().size()*3]
因为其余的代码来自我的教师,大概是正确的。什么可以发送它超出限制的想法?
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;
}
答案 0 :(得分:1)
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;
}
}