2011-03-03 105 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

相关问题