Reputation: 4623
Below is a method that takes in student
array and the topStudentIndex
of 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.length
is 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
Reputation: 936
You want to traverse the entire array using st[i] (not st[nextHighestStudentIndex])
Upvotes: 1
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