因此,我目前正在开发一个函数,它检查给定的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。
1条答案
按热度按时间g2ieeal71#
您的功能
正在检查
time
在roundedStartTime
之后或
x1个月2个月1个月x1个月3个月1个月x1个月4个月
和
time
在roundedEndTime
之前通过查看Java operator precedence table,我们可以得出结论:
&&
的优先级为4,而||
的优先级为3。因此,您的条件是检查(时间等于roundedStartTime且在roundedEndTime之前)还是(时间在roundedStartTime之后)。因此,当您的
time
在roundedStartTime
之后和roundedEndTime
之后时,也就是说,它晚于整个范围,条件的计算结果仍然为true,因为||
的第一个操作数的计算结果为true。要解决这个问题,您需要在||
前后加上括号,这样您的逻辑表达式的计算结果将为(time〉=舍入开始时间)和(时间〈舍入结束时间)
修复: