【问题标题】:What is wrong with this logic statement (Android)?这个逻辑语句(Android)有什么问题?
【发布时间】:2013-01-10 21:33:56
【问题描述】:

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

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

所以我想在光标计数超过 1 时打印 's' 但仅在 componentType 不等于 x 或 y 时才打印 's'..

有趣的是,似乎适用于 y 而不是 x 的情况。

Confused.com! :)

【问题讨论】:

    标签: android logic


    【解决方案1】:

    试试

    if (cursorCount > 1 && !("x".equals(componentType) || "y".equals(componentType)))
    

    你也可以这样做

    if (cursorCount > 1 && !"x".equals(componentType) && !"y".equals(componentType))
    

    这来自于将德摩根定律应用于您的逻辑。

    我相信这些更符合您对您想要的东西的英文描述。

    编辑:

    为了解惑,我们来分析一下你英文描述最后一部分的逻辑:

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

    另一种表述同一事物的方式是“componentType 既不是 x 也不是 y”。为了将它翻译成代码,我们应该更进一步,将这个条件改写为“不是 componentType 是 x 或 comonentType 是 y”。这个最终版本表明正确的布尔公式的形式是

    !(A || B)
    

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

    !A || !B
    

    请注意,我最后的改写更冗长,但多余的措辞使逻辑更清晰。

    另一种分析逻辑的方法是看你给出的代码:

    !"x".equals(componentType) || !"y".equals(componentType)
    

    我们来看几个例子:

    1. "x".equals(componentType) is true. This means the negation is false. It also means that "y".equals(componentType)` 为假,它的 否定为真。因此,您的代码计算结果为 true。

    2. "y".equals(componentType) is true. This means the negation is false. It also means that "x".equals(componentType)` 为假,它的 否定为真。因此,您的代码计算结果为 true。

    3. "x".equals(componentType) nor "y".equals(componentType) 都不为真。这意味着两个否定都是错误的,并且您的代码计算结果为错误。

    请注意,您的代码在 1. 和 2 两种情况下都为 true。这与您的英文描述所期望的结果不同。

    【讨论】:

    • 为快速响应干杯。第一个选项效果很好。不过,我是不是很愚蠢-第二个选项在我测试时如何起作用:this AND (!this or !this).. 认为我自己搞糊涂了!!
    • @Scamparelli 请参阅我的编辑以了解您正在尝试做的事情背后的逻辑。
    【解决方案2】:

    您的“x”条件之前有一个不应该存在的 '('。然后从整个 if 语句的末尾删除其中一个。您应该将那些属于一起的条件包装在 "() " 因为这样读起来真是令人困惑。

    if ((cursorCount > 1 && !"x".equals(componentType)) || (!"y".equals(componentType)))

    【讨论】:

      【解决方案3】:
      if ((cursorCount > 1 && !"x".equals(componentType)) 
      || (cursorCount > 1 && !"y".equals(componentType))) 
        message.append("s");
      

      或者你可以嵌套它们,如果它更容易的话

      if (cursorCount > 1)
        if (componentType!="y" || componentType!="x")
          message.append("s"); 
      

      这样会更容易理解,减少谬误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多