[英]If statement does not work as intended in java
我正在尝试创建一种方法,该方法基本上从对象数组中获取int
值并检查哪个 object 更接近特定值。 我在使用大量if statements
的同时完成了此操作,到目前为止该方法没有打印结果。
在尝试使其正常工作时,我已经编写了如下所示的代码。
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
*/
}
}
}
}
}
IDE 没有向我显示任何错误。 甚至没有代码警告,所以我找不到具体的问题。 如果有人知道这有什么问题,请发表评论或回答。
我怀疑这不是if
,而是for
没有像您预期的那样工作:
for(int j = 0; j != i && j<N; j++)
这将在第一次迭代时立即中断,因为j == i
(== 0)。 for
循环仅在条件为真时执行:当条件为假时它立即停止。
它不会继续推测性地寻找条件可能再次为真的另一个值——一般来说,可能没有这样的值。
我怀疑你的意思是:
for(int j = 0; j<N; j++) {
if (j == i) continue;
// ...
}
它跳过了j == i
的情况,但之后继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.