gymcode
gymcode

Reputation: 4623

For loop containing if statements does not loop again

Below is a method that takes in studentarray and the topStudentIndexof a value calculated by another method previous.

I have multiple objects in my array. However, the for loop only managed to loop through once, and it returned the first value straight away.

I have no clue why the for loop stopped even though my st.lengthis more than

public static int computeNextHighestOverallStudentIndex(Student[] st, int topStudentIndex) {

    double nextHighestOverall= 0;
    int nextHighestStudentIndex = 0;
    for (int i = 0; i < st.length; i++) {
            if ((st[i] != null) && (!(i == topStudentIndex))){
                double studentOverall = st[nextHighestStudentIndex ].getOverall();
                if (studentOverall > nextHighestOverall) {
                    nextHighestOverall= studentOverall;
                    nextHighestStudentIndex = i;
                }
            }
        }
    return nextHighestStudentIndex ;
}

Upvotes: 2

Views: 40

Answers (2)

smaug
smaug

Reputation: 936

You want to traverse the entire array using st[i] (not st[nextHighestStudentIndex])

Upvotes: 1

Eran
Eran

Reputation: 393831

It looks like

double studentOverall = st[nextHighestStudentIndex ].getOverall();

should be

double studentOverall = st[i].getOverall();

since you want to check all the Students in the array and not just the first one (st[nextHighestStudentIndex ] will always return the first Student, since you initialize nextHighestStudentIndex to 0).

Upvotes: 1

Related Questions