2011-03-03 102 views
1

我是編程新手,在eclipse中運行一些新代碼時,遇到了這個錯誤,並且完全丟失了。線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException

import java.util.Scanner; 

public class Lab6 
{ 
    public static void main(String[] args) 
    { 
     // Fill in the body according to the following comments 
    Scanner in= new Scanner(System.in); 
     // Input file name 
     String FileName=getFileName(in); 
     // Input number of students 
     int numOfStudents = FileIOHelper.getNumberOfStudents(FileName); 
     Student students[] = getStudents(numOfStudents); 
     // Input all student records and create Student array and 
     // integer array for total scores 
     int[]totalScores = new int[students.length]; 
     for(int i=0; i< students.length; i++) 
     { 
      for(int j=1; j<4; j++) 
      { 
       totalScores[i]= totalScores[i]+students[i].getScore(j); 
      } 
     } 
     // Compute total scores and find students with lowest and 
     // highest total score 
     int i; 
     int maxIndex =0; 
     int minIndex =0; 
     for(i=0; i<students.length; i++); 
     { 
      if(totalScores[i]>=totalScores[maxIndex]) 
      { 
       maxIndex=i; 
      } 
      else if(totalScores[i]<=totalScores[minIndex]) 
      { 
       minIndex=i; 
      } 
     } 

問題似乎是在該行如果(totalScores [I]> = totalScores [maxIndex])

+0

堆棧跟蹤(與你的ArrayIndexOutOfBoundsException異常開始)的前幾行是至關重要的。 – Satya 2011-03-03 03:42:11

+1

你的代碼中的另一個錯誤是;之後的for()。 – Mudassir 2011-03-03 03:47:21

回答

5

你有一個;你最後for後,所以for,無需額外執行後命令在每個步驟中,變量i將具有students.length的數值範圍之外的值。然後在for後面的{ ... }塊執行一次,最終值爲i,導致異常。

刪除那;它應該工作。

0

在此線問題

INT [] totalScores =新INT [students.length];

的for(int i = 0;我< students.length;我++) { 對(INT J = 1;Ĵ< 4; J ++) { totalScores [I] = totalScores [I] +學生[ I] .getScore(J); } }

您爲totalscore分配了students.length大小..但是您使用的是4 * students.length ..所以arrayindex出現了界限。使用這個

int [] totalScores = new int [4 * students.length];

感謝 arefin

+0

這不是問題,他從來不會像'totalScores [i * j]',只是'totalScores [i]'(和'students [i]')那樣訪問任何東西,所以尺寸是正確的。 – Dan 2011-03-03 04:42:58

相關問題