Home > OS >  If statement does not work as intended in java
If statement does not work as intended in java

Time:11-26

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.

CodePudding user response:

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.

  • Related