线程“main”中的exceptionjava.lang.ArrayIndexOutOfBoundsException

我是编程的新手,在eclipse中运行一些新代码时,我遇到了这个错误并且完全丢失了。

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=totalScores[maxIndex]) { maxIndex=i; } else if(totalScores[i]<=totalScores[minIndex]) { minIndex=i; } } 

问题似乎在行中if(totalScores [i]> = totalScores [maxIndex])

你有一个; 在你的最后一个之后,所以在for执行之后,在每个步骤中没有附加命令,变量i将具有值students.length ,它超出了数组的范围。 然后,for的后面的{ ... }块用i最终值执行一次,导致exception。

删除; 它应该工作。

这方面的问题

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

for(int i = 0; i

你为totalscore分配了students.length大小..但是你正在使用4 * students.length ..所以arrayindex超出了界限。 用这个

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

谢谢你们