这个逻辑语句(Android)出了什么问题?

Sca*_*lli 0 logic android

我不明白为什么以下逻辑不起作用:

                if (cursorCount > 1 && (!"x".equals(componentType) || !"y".equals(componentType))){
                        message.append("s");
                    }
Run Code Online (Sandbox Code Playgroud)

所以我想打印's'如果光标数超过1,但只有当componentType不等于x或y时才打印's'.

似乎适用于y但不是x有趣的案例.

Confused.com!:)

Cod*_*ice 5

尝试

if (cursorCount > 1 && !("x".equals(componentType) || "y".equals(componentType)))
Run Code Online (Sandbox Code Playgroud)

等价的你可以做到

if (cursorCount > 1 && !"x".equals(componentType) && !"y".equals(componentType))
Run Code Online (Sandbox Code Playgroud)

这来自deMorgan定律适用于您的逻辑.

我相信这些更接近你对你想要的英语描述.

编辑:

为了消除困惑,让我们分析一下你英文描述的最后部分的逻辑:

...但仅当componentType不等于x或y时.

陈述相同事物的另一种方式是"componentType既不是x也不是y".为了将其转换为代码,我们应该更进一步,并将此条件改为"不是componentType为x或comonentType为y的情况".最终版本表明正确的布尔公式是形式

!(A || B)
Run Code Online (Sandbox Code Playgroud)

这与您原始代码的形式非常不同

!A || !B
Run Code Online (Sandbox Code Playgroud)

请注意,我的最终重写更详细,但额外的措辞使逻辑更清晰.

分析逻辑的另一种方法是查看您提供的代码:

!"x".equals(componentType) || !"y".equals(componentType)
Run Code Online (Sandbox Code Playgroud)

我们来看几个例子:

  1. "x".equals(componentType) is true. This means the negation is false. It also means that"y".equals(componentType)`是false,它的否定是真的.因此,您的代码评估为true.

  2. "y".equals(componentType) is true. This means the negation is false. It also means that"x".equals(componentType)`是false,它的否定是真的.因此,您的代码评估为true.

  3. 无论是"x".equals(componentType) nor"Y" .equals(组件类型)是真实的.这意味着两个否定都是错误的,您的代码评估为false.

请注意,在两种情况下,您的代码的计算结果为真1.和2.这不会产生与您的英语描述相同的结果.