1

I am writing a program that stores a student's name, student number and his grade for a course in a textfile.

Now I am writing the method for accessing the grade of the student. The method gets the desired student number as input. In the code below I get the error
java.lang.ArrayIndexOutOfBoundsException, for the lines:
System.out.println(studentFile [1]); and the if statement.

I think I am accessing the element in the wrong way but I am not 100% sure. The rest of methods work like a breeze.

public  static void getGradeOfStudentNumber(String studentNumberForGrade){
        try
        {
        String line;
        BufferedReader br = new BufferedReader(new
        FileReader("StudentArchive.txt"));
        while((line = br.readLine())!= null)
        {
        String[] studentFile = line.split(",");
        System.out.println(Arrays.toString(studentFile));
        System.out.println(studentFile [1]);
         /*if ((studentFile[1]).equals(studentNumberForGrade))
        {

         String grade = studentFile[2];
         System.out.println("the student's grade is "+ grade);

        }*/
        }
        br.close();
        }
        catch (IOException ex)
        {
        System.out.println("The file does not exist");
        }
    }       
}
Justin
  • 24,288
  • 12
  • 92
  • 142
Niels
  • 35
  • 3
  • 1
    Are you sure `line.split(",")` returns 2 elements? An example of the line is needed here. – jAC Feb 21 '16 at 10:09
  • Your index will be out of bounds only if your line does not have a comma. – Idos Feb 21 '16 at 10:10
  • System.out.println(Arrays.toString(studentFile)); Returns arrays that look like [ Name, 4444, 6.0] Being the name, student number and grade respectively – Niels Feb 21 '16 at 10:16

1 Answers1

0

Before retrieving the data from array check if the length more than 2 of the array:

    if(studentFile.length>=2)
    System.out.println(studentFile[1]);
Abdelhak
  • 8,299
  • 4
  • 22
  • 36