private List<Double[]> bestPoints(List<Double[]> includedPoints) {
List<Double[]> bestPoints = new ArrayList<Double[]>();
int a = includedPoints.size();
for (int i = 0; i < a; i++) {
Double[] tempPoint = includedPoints.get(i);
if (tempPoint[2] == maxCount) {
bestPoints.add(new Double[] {tempPoint[0], tempPoint[1]});
}
}
return bestPoints;
}
在这种情况下
a = 17
maxCount = 2.0
和
tempPoint[2]
在这种情况下每次都是 2.0
但是调试器显示
bestPoints.add(new Double[] {tempPoint[0], tempPoint[1]});
只运行一次,就好像 if 语句不正确一样?为什么?
最佳答案
您很可能执行引用等于而不是比较等于。使用数字类型的大写字母版本时,应使用 one.equals(two)
。
确保 tempPoint[2]
的值恰好 2.0
。作为double
,它们很可能很接近,但不相等。
您可能还会发现使用 foreach 循环更容易理解:
private List<Double[]> bestPoints(List<Double[]> includedPoints) {
List<Double[]> bestPoints = new ArrayList<Double[]>();
for (Double[] tempPoint : tempPoints) {
if (tempPoint[2] == maxCount) {
bestPoints.add(new Double[] { tempPoint[0], tempPoint[1] });
}
}
return bestPoints;
}
如果值始终为整数,则在检查相等性之前对它们进行转换(例如,(long)tempPoint[2] == (long)maxCount
)。如果您想要从 double
中精确匹配,则继续您正在做的事情(在确保相等检查的正确类型之后,取决于 maxCount),但如果您想要接近匹配(如果需要考虑小数而不是预定义常量),则使用 epsilon 值:
public static boolean doubleEquals(double val1, double val2, double epsilon)
{
return Math.abs(val1 - val2) < epsilon;
}
public static boolean doubleEquals(double val1, double val2)
{
return doubleEquals(val1, val2, 1e-5);
}
显然指定一个对您有意义的 epsilon 值。
关于java - for循环中的if语句只返回true一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5813826/