简体   繁体   中英

If statement does not work as intended in java

I am trying to create a method that basically takes int values from an array of objects and checks which object is closer to a specific value. I have done this while using numerous if statements and so far the method doesn't print an outcome.

I have written this code as shown below while trying to make this work properly.

public void teamlengthaverage(int N) {
    for (int i = 0; i < N; i++) {
        if (teams[i].getScore() <= mesoScore(N)) {
            for (int j = 0; j != i && j < N; j++) {
                if (teams[i].getScore() > teams[j].getScore()) {
                    System.out.print(
                            "The team closest to the average score is: "
                                    + teams[i]);
                    }
                }
            }
        } else if (teams[i].getScore() >= mesoScore(N)) {
            for (int j = 0; j != i && j < N; j++) {
                if (teams[i].getScore() < teams[j].getScore()) {
                    System.out.print(
                            "The team closest to the average score is: "
                                    + teams[i]);

                    /*
                     * the program checks if a value above or below the
                     * value of mesoScore is closer to it while also
                     * different to other values in the array as well
                     */
                }
            }
        }
    }
}

The IDE isn't showing me any errors. Not even a warning for the code so I cannot find the issue specifically. If anyone has an idea to what is wrong with this please comment or answer.

I suspect that it's not the if , it's the for that's not working as you expect:

for(int j = 0; j != i && j<N; j++)

This will break immediately on the first iteration because j == i (== 0). A for loop only executes while the condition is true: it stops immediately when the condition is false.

It doesn't carry on speculatively looking for another value for which the condition might be true again - in general, there may be no such value.

I suspect that you mean instead:

for(int j = 0; j<N; j++) {
  if (j == i) continue;

  // ...
}

which skips over the case where j == i , but continues after.

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