-1

This program displays false results in the 2nd line B, if the first sentence is true, he considers the 2nd condition true without testing. can you offer me sulutions:

int N=10, P=5;
char C='S';
boolean B;

N=5;P=2;
B= (N++>P)||(P++ !=3);
System.out.println("A : N= "+N+" P="+P+" B="+B);

N=5; P=2;
B= (N++ <P)|| (P++ !=3);
System.out.println("B : N= "+N+" P="+P+" B="+B);

N=5; P=2;
B= (++N ==3) && (++P ==3);
System.out.println("C : N= "+N+" P="+P+" B="+B);

N=5; P=2;
B= (++N ==6) && (++P ==3);
System.out.println("D : N= "+N+" P="+P+" B="+B);

N=C;
System.out.println("\nE :C= "+C+" N = "+N);

[enter image description here][1]

[1]: https://i.stack.imgur.com/Le5lE.png result of the program

  • `P` (which is 2 at that moment) is not equal to 3 and then you wonder why 2 != 3 is true? Really? – Tom Nov 23 '17 at 14:35
  • @OHGODSPIDERS But the first one is false, so it has to check the second statement. – Tom Nov 23 '17 at 14:38
  • @Tom Ahh, now i see. I got confused by the "if the first sentence is true" in the question. What actually is the case here is that `P++!=3` is evaluated and is true if `P=2`. Thats because of how the post increment works. – OH GOD SPIDERS Nov 23 '17 at 14:45
  • Don't use the ++, --, +=, etc operators in an if condition unless you really understand what you are doing. – rghome Nov 23 '17 at 14:54

3 Answers3

1

That's how OR works. Only one of the ORed expressions needs to be true for the whole expression to be true, so testing stops at the first one to evaluate to true. If you want your expression to fail if one subexpression is false, use AND (&&).

Todd
  • 4,669
  • 1
  • 22
  • 30
0

Okay, why don’t you use “++P” instead of “P++”? It may first compare the current value of P (which is 2) with the number 3 and then P gets incremented. If you use “++P” you will change the order of the actions.

DrunkCoder
  • 83
  • 1
  • 10
0

The program outputs in the pic are correct.
Logical operator || "OR" return true if at least one of the sentences is true, so there's no need to look also to the next sentence if the first is true; in fact, for every value the second sentence can assume, the sentence B= (N++ <P)|| (P++ !=3); will be true.
Probably did you mean the exclusive or (XOR) ^, that is true only if a sentence is true and the other is false?

Jul10
  • 503
  • 7
  • 19