简体   繁体   English

如果语句在 java 中没有按预期工作

[英]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.我正在尝试创建一种方法,该方法基本上从对象数组中获取int值并检查哪个 object 更接近特定值。 I have done this while using numerous if statements and so far the method doesn't print an outcome.我在使用大量if statements的同时完成了此操作,到目前为止该方法没有打印结果。

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. IDE 没有向我显示任何错误。 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:我怀疑这不是if ,而是for没有像您预期的那样工作:

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

This will break immediately on the first iteration because j == i (== 0).这将在第一次迭代时立即中断,因为j == i (== 0)。 A for loop only executes while the condition is true: it stops immediately when the condition is false. for循环仅在条件为真时执行:当条件为假时它立即停止。

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.它跳过了j == i的情况,但之后继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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