debugging 比较LocalTime返回true,即使调试器计算结果为false

6rqinv9w  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(122)

因此,我目前正在开发一个函数,它检查给定的LocalTime是否在一个范围内。一切都很好,LocalDateTime的等效函数也没有问题。
所以,我的代码现在看起来像这样:

public boolean isInRange(LocalTime time){
        return (time.isAfter(roundedStartTime.toLocalTime())) || time.equals(roundedStartTime.toLocalTime()) &&
            time.isBefore(roundedEndTime.toLocalTime());
    }

它有一些关于我的业务逻辑的细节,但这不是问题的一部分。我还附带了junit测试,检查逻辑是否按预期工作。同样,inRange(LocalDateTime time)函数工作得很完美。
但是使用我的测试,* 使用我用于 * LocalDateTime * 验证 * 的相同时间,它们失败了,因为它们不知何故返回true。我已经开始调试,并且不能完全相信我的眼睛,这解释了true && false检查:

无论出于何种原因,单独评估这两个语句都会显示预期的行为,但将它们组合在一起会返回true。

g2ieeal7

g2ieeal71#

您的功能

public boolean isInRange(LocalTime time){
        return (time.isAfter(roundedStartTime.toLocalTime())) || time.equals(roundedStartTime.toLocalTime()) &&
            time.isBefore(roundedEndTime.toLocalTime());
    }

正在检查
timeroundedStartTime之后

x1个月2个月1个月x1个月3个月1个月x1个月4个月

timeroundedEndTime之前
通过查看Java operator precedence table,我们可以得出结论:&&的优先级为4,而||的优先级为3。因此,您的条件是检查(时间等于roundedStartTime且在roundedEndTime之前)还是(时间在roundedStartTime之后)。
因此,当您的timeroundedStartTime之后和roundedEndTime之后时,也就是说,它晚于整个范围,条件的计算结果仍然为true,因为||的第一个操作数的计算结果为true。要解决这个问题,您需要在||前后加上括号,这样您的逻辑表达式的计算结果将为
(time〉=舍入开始时间)和(时间〈舍入结束时间)
修复:

public boolean isInRange(LocalTime time){
        return ((time.isAfter(roundedStartTime.toLocalTime())) || time.equals(roundedStartTime.toLocalTime())) &&
            time.isBefore(roundedEndTime.toLocalTime());
    }

相关问题