2017-09-12 35 views
0

我正在嘗試計數數組以跟上一組50個選項,其中每個選項有三個選項。計數陣列應該有150個元素,每個教師(3 x 50 = 150)。但我一直在第55行(index = thisChoice.get(i))收到IndexOutofBounds異常。我想,它必須有一些做與如何(或在哪裏?)我在實例實例化數組,但不斷獲取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

什麼是55行? –

+0

添加到我原來的帖子。對不起,我把它丟掉了! –

+0

仔細看看給你的例外。你犯了一個錯字。 – ajb

回答

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; 
     } 
    }