【问题标题】:Triple Conditioned Do-While Loop With Multiple Logical Operators具有多个逻辑运算符的三重条件 Do-While 循环
【发布时间】:2018-05-12 20:17:49
【问题描述】:

我无法让下面的 do-while 循环在 Java 中工作。感谢您的帮助。

do{
//User enters a value for x
//User enters a value for y
}while(x==-1 && y==-1 || x==5 || y==10);

我想要做的只是:
a) 如果 x 和 y 均为 -1,则终止循环
b) 如果 x 为 5 或 y 为 10,则终止循环

【问题讨论】:

  • 怎么回事,描述一下当前的行为/错误

标签: java do-while logical-operators boolean-logic eclipse-oxygen


【解决方案1】:

你把问题放在了错误的一边。您的循环将在您想要停止的地方继续

您应该简单地执行以下操作并反转条件

do {

} while (!(x == -1 && y == -1 || x == 5 || y == 10));

Demo

public static void main (String[] args) {
    System.out.println(conditionTesting(0, -1));  // true
    System.out.println(conditionTesting(-1, -1)); // false
    System.out.println(conditionTesting(5, -1));  // false
    System.out.println(conditionTesting(-1, 10)); // false
    System.out.println(conditionTesting(6, 9));   // true
}

public static boolean conditionTesting(int x, int y) {
    return !(x == -1 && y == -1 || x == 5 || y == 10);
}

德摩根

如果你想用DeMorgan's Law去代表它,你可以使用以下步骤来完成

¬((P ∧ Q) ∨ R ∨ S)
≡¬(P ∧ Q) ∧ ¬R ∧ ¬S
≡(¬P ∨ ¬Q) ∧ ¬R ∧ ¬S

所以你的最终翻译是

(x != -1 || y != -1) && x != 5 && y != 10

Ideone Demo

【讨论】:

  • 是的,我忘了加“!”在示例中的“=”之前。但是,我不明白的是: while(x!=-1 && y!=-1 || x!=5 || y!=10) 不起作用但是 while(!(x==-1 && y==-1 || x==5 || y==10)) 完美运行。他们不是一样的吗?这只是不同的符号,但第二个仍然可以完美地工作,而第一个根本不起作用。
  • 其实它们根本不是一回事。如果你像我一样添加!,它会否定 whole 表达式。之前评估为true 的表达式将在之后评估为false
  • 根据德摩根定律,将否定分配给析取和合取应该如下: ¬(P∨Q)≡(¬P∧¬Q) 和 ¬(P∧Q)≡(¬P∨ ¬Q)。这就是为什么它们不一样,这就是我猜我感到困惑的原因。
  • @Caglar 好吧,我添加了一些关于如何使用德摩根定律翻译表达式的解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多