1

I'm having a bit of trouble with this project:

We're given a text file of 5 students, with 4 number grades following each name in a separate line. We have to use our main method to read the file, then perform calculations in the gradebook class. However, from what others in class have been saying the method we're using is archaic at best, involving Parallel arrays. We don't really seem to have any other option though, so I'm making due with what I can. But near what I'm hoping is the end of this code, I've encountered a problem, where it says the index that contains the grades for students is out of bounds.

I've rewritten the readFile method in my main in quite a few different ways, but no matter what I still get these errors. Could anyone help me understand what's going on? I'll post everything I can. I also apologize if I'm a bit slow/incapable with this, this is my first time coding java in months unfortunately.

Also, in the error I post, line 64 of the main class is: grades[test] = inputFile.nextDouble();

run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Package1.GradeBookDemo.readFile(GradeBookDemo.java:64)
    at Package1.GradeBookDemo.main(GradeBookDemo.java:29)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

The following is my Main method:

import java.util.Scanner;
import java.io.*;

public class GradeBookDemo {

    public static void main(String[] args) throws IOException {

        // Create a new gradebook object
        Gradebook gradeBook = new Gradebook();

        //Read StudentInfo file for names and test scores using readFile method
        readFile(gradeBook);

        //Output Student data
        for (int index = 1; index <= 5; index++)
        {
            System.out.println("Name: " + gradeBook.getName(index) + 
                    "\tAverage Score: " + gradeBook.getAverage(index) +
                    "\tGrade: " + gradeBook.getLetterGrade(index));
        }

    }


    // This method reads from the StudentInfo file
    public static void readFile(Gradebook gradeBook) throws IOException
    {

        int nI = 0; // Name index
        int gI = 4; // Grade index

        // Create a string array to hold student names and another for grades
        double[] grades = new double[gI];

        // Access the StudentInfo text file
        File sFile = new File("StudentInfo.txt");
        // Create a scanner object to read the file
        Scanner inputFile = new Scanner(sFile);

        // Read StudentInfo
        for(int student = 1; student <= 5; student++)
        {
            String name = inputFile.nextLine();
            gradeBook.setName(student, name);
            for (int test = 0; test < 4; test++)
            {
                grades[test] = inputFile.nextDouble();
            }
        }

    // Close the file
    inputFile.close();

    }

}

And then the Gradebook class

public class Gradebook {

    // Declare fields
    private final int NUM_STUDENTS = 5;
    private final int NUM_TESTS = 4;
    // ArrayList for names of students - 5 in total
    private String[] names = new String[NUM_STUDENTS];
    // Array to store letter grades
    private char[] grades;
    // array to store each student's scores
    private double[] scores1 = new double[NUM_TESTS];
    private double[] scores2 = new double[NUM_TESTS];
    private double[] scores3 = new double[NUM_TESTS];
    private double[] scores4 = new double[NUM_TESTS];
    private double[] scores5 = new double[NUM_TESTS];


    // Method to set student's name
    public void setName(int studentNumber, String name)
    {
        names[studentNumber-1] = name;
    }

    // Method sets student scores

    public void setScores(int studentNumber, double[] scores)
    {
    switch(studentNumber)
        {
            case 1:copyArray(scores1,scores); break;
            case 2:copyArray(scores2,scores); break;
            case 3:copyArray(scores3,scores); break;
            case 4:copyArray(scores4,scores); break;
            case 5:copyArray(scores5,scores); break;
            default:break;
        }
    }

    // Returns the student's name

    public String getName(int studentNumber)
    {
    return names[studentNumber-1];
    }

    // Returns student's average score

    public double getAverage(int studentNumber)
    {
    double avg=0.0;
    switch(studentNumber)
    {
        case 1:avg = calcAverage(scores1); break;
        case 2:avg = calcAverage(scores2); break;
        case 3:avg = calcAverage(scores3); break;
        case 4:avg = calcAverage(scores4); break;
        case 5:avg = calcAverage(scores5); break;
        default:break;
    }
    return avg;
    }

    // Returns the student's letter grade

    public char getLetterGrade(int studentNumber)
    {
    char lettergrade;
    if(getAverage(studentNumber)>=90 && getAverage(studentNumber)<=100)
            lettergrade = 'A';
    else if(getAverage(studentNumber)>=80 && getAverage(studentNumber)<=89)
        lettergrade = 'B';
    else if(getAverage(studentNumber)>=70 && getAverage(studentNumber)<=79)
        lettergrade = 'C';
    else if(getAverage(studentNumber)>=60 && getAverage(studentNumber)<=69)
        lettergrade = 'D';
    else
            lettergrade = 'F';
    return lettergrade;

    }

    // Calculates the student's average

    private double calcAverage(double[] scores)
    {
    double sum=0;
    for(int i=0; i<scores.length; i++)
            sum+=scores[i];
    return sum/scores.length;

    }

    // Determines student's letter grade based on average score

    public char LetterGrade(double average)
    {
    char lettergrade;
    if(average>=90 && average<=100)
        lettergrade = 'A';
    else if(average>=80 && average<=89)
        lettergrade = 'B';
    else if(average>=70 && average<=79)
        lettergrade = 'C';
    else if(average>=60 && average<=69)
        lettergrade = 'D';
    else
            lettergrade = 'F';
    return lettergrade;
    }

    // Array copy method
    private void copyArray(double[] to, double[] from)
    {
    System.arraycopy(from, 0, to, 0, from.length);
    }


}

Here is the file the program is reading - StudentInfo.txt:

Joanne Smith
98
89
100
76
Will Jones
67
89
91
88
Kerry McDonald
78
79
88
91
Sam Young
88
98
76
56
Jill Barnes
94
93
91
98
8
  • I have tried it and it works for me without problem. Try to clean and rebuild your project. Commented Oct 9, 2014 at 6:14
  • That's odd, It still gives me the same error. I'll try in a different compiler maybe. Commented Oct 9, 2014 at 6:23
  • maybe your file data is incorrect, as the exception occurs at readFile() Commented Oct 9, 2014 at 6:25
  • @Alzecha Which line is line 64 in GradeBookDemo Commented Oct 9, 2014 at 6:29
  • 1
    @DanielBarbarian i did the same :) sorry too :) Commented Oct 9, 2014 at 11:15

2 Answers 2

1

You will get InputMismatchException

Reason
String name = inputFile.nextLine(); //Reads the current line, Scanner moves to next line
grades[test] = inputFile.nextDouble(); //Reads the next double value

You should be able to read first student name and grades without any issues. After reading 76, the scanner position is at the end of line 5. It didn't skip line 5.

So, when you try to read next student name by calling nextLine(). you will see "". and scanner moves to line 6.

So the next call to nextDouble() fails.

Quick fix
use Double.parseDouble(inputFile.nextLine()); for reading the double values here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton for the help, sorry for the delay on my answer, I had to take a break from this. I attempted to insert that in place of grades[test]=inputfile.nextDouble();, but putting it like that gave me another mismatch error. After that I tried putting grades[test]= before it, but that won't compile. I wasn't sure if I just misread where I should put it or if I've just still got an error. I'll keep trying though
You should be able to run it after changing to this. grades[test] = Double.parseDouble(inputFile.nextLine()); Please update exception trace here.
0

This is a rather interesting "This can not happen" scenario. From the comments I would guess that the code actually compiled has an error in the inner for-loop. You need to find which file you are actually compiling.

Try adding random

System.out.println("Got HERE!");

to your code and see if any of them are actually printed. Because the code you show should not be able to give that exception.

2 Comments

Thanks for the reply. Oddly enough, I did this and none of them are printing. I get mismatch exception again, both with my original code and attempting what Suresh said in the above comment. It's really starting to confuse me on why parts from even the earlier code can't print text...
@Alzecha the answer to this question is easy, the file the compiler sees is not the one you are editing. Considering that you got behavioural changes randomly you are probably compiling some one elses file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.