简体   繁体   中英

Integer does not compare when not equals

I have a method that calculate the next top score within an array of students by taking in the student array and topStudentIndex as parameters, which is calculated by another method for topStudentIndex in my main.

Below is my method:

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

    double nextHighestOverall= 0;
    int secondHighestStudentIndex = 0;
    for (int i = 0; i < st.length; i++) {
        if ((st[i] != null) && (!(st[i].getStudentIndex() == topStudentIndex))) {
            System.out.println(topStudentIndex+ " compare with i = "+i);
            double currentOverall= st[i].getOverall();
            if (currentOverall> nextHighestOverall) {
                nextHighestOverall= currentOverall;
                secondHighestStudentIndex = i;
            }
        }
    }
    return secondHighestStudentIndex ;
}

I take in the index position of the top student, and checks if the array position is empty && same index. If not, the check will proceed.

However, the output shows that the comparison of index position is not working.

1 compare with i = 0
1 compare with i = 1
1 compare with i = 2
1 compare with i = 3
1 compare with i = 4
1 compare with i = 5
1 compare with i = 6

I have tried using != and my current way of checking but to no avail.

if ((st[i] != null) && (!(st[i].getStudentIndex() == topStudentIndex))) {
            System.out.println(topStudentIndex+ " compare with i = "+i);

You are comparing topStudentIndex with st[i].getStudentIndex() but printing i in the print statement.

Either do

if ((st[i] != null) && (!(i == topStudentIndex)))

or print

 System.out.println(topStudentIndex+ " compare with student index = "+ st[i].getStudentIndex());

to get clear idea why comparison fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM