我有一个java程序,我想验证3个布尔值中的任何一个是否为假。我想弄清楚我可以编写的最小的表达式来检查排列。
if(!(needsWork && (needsApproval || isAdmin) ))
我认为这足以确保如果3个布尔中的任何一个是假的,我想停止处理。但是,我怀疑我错过了一些东西。
答案 0 :(得分:7)
if (!needsWork || !needsApproval || !isAdmin)
不起作用吗? Java支持短路评估。
答案 1 :(得分:6)
由于
`any 3 booleans are false` (i.e. `!a || !b || !c`)
和
`(! (needsWork && (needsApproval || isAdmin))` (i.e. (! (a && ( b || c))`
有不同的真值表 ,您确定不同的案例无关紧要吗?
a b c (!a || !b || !c) (! (a && (b || c)))
T T T F F
T T F T F
T F T T F
T F F T T
F T T T T
F T F T T
F F T T T
F F F T T
的转换强> 的
我会经常使用布尔表达式来尝试澄清或简化它们,并使用这些逻辑转换来帮助我:
// You can push (distribute) `!` into parenthesis if you reverse the `||` or `&&` operator inside:
! (a || b) <=> (! a && ! b)
! (a || b || c || ...) <=> (! a && ! b && ! c && ...)
! (a && b) <=> (! a || ! b)
! (a && b && c && ...) <=> (! a || ! b || ! c || ...)
// You can drop parens when the boolean operator outside the parens is the same as inside:
(a || (b || c || ...)) <=> (a || b || c)
(a && (b && c && ...)) <=> (a && b && c)
// You can push (distribute) a boolean op into parenthesis by applying it to each term inside:
(a || (b && c) <=> ((a || b) && (a || c)
(a || (b && c && ...) <=> ((a || b) && (a || c) && (a || ...) ...
(a && (b || c) <=> ((a && b) || (a && c))
(a && (b || c || ...) <=> ((a && b) || (a && c) || (a || ...) ...
// XOR means the term values have to be different:
(a ^ b) <=> ((a && !b) || (!a && b))
// XOR means the same as OR unless both terms are true:
(a ^ b) <=> ((a || b) && ! (a && b))
当然还有很多其他的,但这些是我经常使用的。它可能看起来很复杂,但是一旦你开始练习它们就很容易被人们所了解。
在您的情况下,如果您想查看一些可能的等效语句:
(! (needsWork && (needsApproval || isAdmin) ))
这里有一些转换:
(! (needsWork && (needsApproval || isAdmin) )) => [push the '!' through the `()`]
(! needsWork || ! (needsApproval || isAdmin) ) => [push the 2nd '!' through the `()`]
(! needsWork || (! needsApproval && ! isAdmin))
但我没有看到你所拥有的任何真正的简化。
当然,如果检查any of 3 booleans are false
没问题,那么您的选择很简单
(! needsWork || ! needsApproval || ! isAdmin) => [or pull the `!` outside the `()`]
(! (needsWork && needsApproval && isAdmin))
答案 2 :(得分:2)
if(!(needsWork & needsApproval & isAdmin))