java - for循环中的if语句只返回true一次?

标签 java for-loop if-statement

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/

相关文章:

javascript - 如果工作,为什么这个 javascript 不与 else 一起使用?

python - 带有 `try` 异常消息的条件 "general"语句

java - hibernate ,获取重复值

java - 如何创建基于注释的 Hibernate 映射?

.html 模板页面中的 django for 循环(新手)

java - 将字符串列表转换为包含这些字符串作为字段的对象列表

r - R中的for循环简单,在R中产生 "replacement has length zero"

java - 无法访问java项目中的文本文件

java - 如何使用 JAVA PKCS11 IAIK 在 SOFTHSM2 中进行 key 包装期间切换到 CKM_AES_KEY_WRAP_PAD

C - 程序只执行 if else 语句的一部分