1

I am new to programming and while running some new code in eclipse, I came across this error and am completely lost.

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

problem seems to be in the line if(totalScores[i]>=totalScores[maxIndex])

Jeff
  • 11
  • 1
  • 1
  • 3

2 Answers2

5

You have a ; after your last for, so after the for executes with no additional commands in each step, the variable i will have the value students.length which is outside the bounds of the array. Then the { ... } block following the for is executed once with that final value of i, causing the exception.

Remove that ; and it should work.

Dan
  • 3,490
  • 2
  • 22
  • 27
0

problem in this lines

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

you allocated students.length size for the totalscore.. but u are using 4*students.length.. so arrayindex out of bounds occured. use this

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

thanks arefin

stinepike
  • 54,068
  • 14
  • 92
  • 112
  • that's not the problem, he never accesses anything like `totalScores[i*j]`, just `totalScores[i]` (and `students[i]`), so the size is right. – Dan Mar 03 '11 at 04:42