1


我有一个 java 程序,我想验证 3 个布尔值中的任何一个是否为假。我想找出我可以写来检查排列的最小表达式。

if(!(needsWork && (needsApproval || isAdmin) ))

我认为这足以确保如果 3 个布尔值中的任何一个为假,我想停止处理。但是,我偷偷地怀疑我错过了一些东西。

4

3 回答 3

7

if (!needsWork || !needsApproval || !isAdmin)行不通?Java 支持短路求值。

于 2010-10-31T22:47:41.630 回答
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))
于 2010-11-01T00:05:40.033 回答
2
if(!(needsWork & needsApproval & isAdmin))
于 2010-10-31T22:47:23.940 回答