2

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

2 Answers 2

1

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).

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

1 Comment

thank you @Eran, after changing it worked. I will accept your answer in a moment, for the timer to expire
1

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

Comments

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.