Java 正在实例化数组,但不断获取IndexOutOfBounds异常
我试图统计一个计数数组,以跟上一组50个选项,其中每个选项有三个选项。根据我的指导老师,计数数组应该有150个元素(3 x 50=150)。但是我一直在第55行得到一个IndexOutofBounds异常(Java 正在实例化数组,但不断获取IndexOutOfBounds异常,java,arrays,Java,Arrays,我试图统计一个计数数组,以跟上一组50个选项,其中每个选项有三个选项。根据我的指导老师,计数数组应该有150个元素(3 x 50=150)。但是我一直在第55行得到一个IndexOutofBounds异常(index=thisChoice.get(I))。我认为这一定与我如何(或在哪里?)实例化我的count数组有关 line 50: int[] count = new int[students.get(0).getChoices().size()*3] 因为剩下的代码来自我的指导老师,大概是
index=thisChoice.get(I)
)。我认为这一定与我如何(或在哪里?)实例化我的count数组有关
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;
}
公共类驱动程序{
公共静态void main(字符串[]args)引发IOException{
ArrayList students=新ArrayList();
ArrayList选项=新建ArrayList();
Scanner scan1=新扫描仪(新文件(“Choices.txt”);
Scanner scan2=新扫描仪(新文件(“EitherOr.csv”);
//扫描第一个文件。
int choicesIndex=0;
while(scan1.hasNextLine()){
String line=scan1.nextLine();
选项。添加(行);
choicesIndex++;
}
scan1.close();
//扫描第二个文件。
int studentIndex=0;
while(scan2.hasNextLine()){
String line=scan2.nextLine();
String[]splits=line.split(“,”);
添加(新学生(拆分[0]);
对于(int i=1;i
您好,请检查第二个嵌套循环,它应该是j
而不是i
。
此外,您还没有在该循环中使用intj
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;
}
}
for(int i=0;i
第55行是什么?添加到我原来的帖子中。很抱歉,我遗漏了它!仔细看看给你一个例外的那行。你打错了。在第55行?为了我的生命,我无法发现它。它应该是get(j)而不是get(I)吗?你写了代码,所以你应该知道它应该做什么,如果它应该是get(I)
或get(j)
。