0

I'm unable to get the do-while loop below work in Java. Thanks for your help.

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

What I'm trying to do is simply:
a) If x and y BOTH are -1 then terminate the loop
b) If x is 5 OR y is 10 then terminate the loop

Çağlar
  • 81
  • 2
  • 8

1 Answers1

1

You took the problem on the wrong side. There your loop will continue where you want to stop.

You should simply do the following and reverse the condition

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

If you want to go and represent it using DeMorgan's Law, you can do it using the following steps

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

So your final translation would be

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

Ideone Demo

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • Yes, I forgot to add '!' before '=' in the example. But, what I don't understand is: while(x!=-1 && y!=-1 || x!=5 || y!=10) doesn't work but while(!(x==-1 && y==-1 || x==5 || y==10)) works perfectly. Aren't they the same thing? It's just different notation but still second one works perfectly while first one doesn't work at all. – Çağlar May 12 '18 at 21:03
  • Well actually they're not the same thing at all. If you add `!` like I did, it negates the **whole** expression. An expression evaluated to `true` before would be evaluated to `false` after – Yassin Hajaj May 12 '18 at 21:06
  • According to De Morgan's laws distributing negation over disjunction and conjunction should be as follows: ¬(P∨Q)≡(¬P∧¬Q) and ¬(P∧Q)≡(¬P∨¬Q). That's why they are not the same and that's why I got confused I guess. – Çağlar May 12 '18 at 21:38
  • @Caglar Alright I added a little explanation on how to translate the expression using the DeMorgan's Laws – Yassin Hajaj May 12 '18 at 22:06