Search code examples
javafor-loopcalculatorindexoutofboundsexceptiongpa

How to make my sum method, which uses a for loop on a list, work correctly?


I am writing a program to calculate GPA and print a transcript. I am having some issues with the methods I have created to get the sum of a semesters gpa. Here's relevant code:

    double sumGP;
    ArrayList<Double> semesterGPs = new ArrayList<Double>();
    public void getGPs(double aGP) {
        semesterGPs.add(aGP);
    }
    public double getTotalGP() {
        for(int i = 0; i <= this.semesterGPs.size(); i++)                        
            sumGP = sumGP + this.semesterGPs.get(i);                            
        return sumGP;   

Here is those blocks of code are used in the main method, as well as relevant main method code:

        Scanner letterGrade = new Scanner(System.in);

            System.out.print("Enter the letter grade recieved if the course is completed, otherwise enter null: ");
            aLetterGrade = letterGrade.next();
            if ((aLetterGrade.contentEquals("a")) || (aLetterGrade.contentEquals("A"))) {
                double aGPRecieved = 4.0;
                //gradePoints.add(aGPRecieved);
                aSemesterGrade.getGPs(aGPRecieved);
                aTotals.getGPs(aGPRecieved);
                System.out.println(aGPRecieved);

            }

aSemesterGrade.getTotalGP();

My for loop keeps throwing an index out of bounds error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Unknown Source)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Unknown Source)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Unknown Source)
    at java.base/java.util.Objects.checkIndex(Unknown Source)
    at java.base/java.util.ArrayList.get(Unknown Source)
    at realGPA/realGPA.SemesterGrades.getTotalGP(SemesterGrades.java:50)
    at realGPA/realGPA.MainController.main(MainController.java:186)

I have already printed out the info from the ArrayList "semesterGPs", so I know the method is actually adding the info to the list, even two or three entries. I am very confused on why the index is out of bounds.


Solution

  • The length of an array is one greater than the final index (indices start at 0)

    public double getTotalGP() {
            for(int i = 0; i < this.semesterGPs.size(); i++)                        
                sumGP = sumGP + this.semesterGPs.get(i);                            
            return sumGP;   
    

    If an array is of N length, array[N] will trigger an index out of bounds error.