Reputation: 359
I have tried to search as much as I can but it's kinda hard when you are a beginner. Anyway im trying to learn Java and im stuck on a question that says "var1 can be bigger than var2 or var3 but not both. And im supposed to answer with a Boolean value.
e = var1 > var2 || var1 > var3 && var1 < var2 + var3;
If I do this I end up with it just doing a total sum of var2 and var3. How do I do like
var1 < var2 AND var3;
Upvotes: 3
Views: 304
Reputation: 878
If var1
"can" be bigger than var2
, and "can" be bigger than var3
, but not both, the answer is pretty simple.
boolean response = !(var1>var2 && var1>var3)
boolean response = (var1<=var2 || var1<=var3)
Upvotes: 4
Reputation: 129537
You can use the exclusive-OR operator:
(var1 > var2) ^ (var1 > var3)
A ^ B
is true
if and only if either A
or B
(but not both) are true
:
A B A^B --------- 0 0 0 0 1 1 1 0 1 1 1 0
Upvotes: 7
Reputation: 2112
Generally you need to consider associativity of operators (usually left to right in Java) as well as operator precedence (multiplication before addition and so on)
var1 can be bigger than var2 or var3 but not both
(var1 > var2 || var1 > var3) && !(var1 > var2 && var1 > var3)
Or you can use exclusive or operator as suggested in one of the other answers which requires the least code.
Upvotes: 0
Reputation: 837
Determine what the bigger one of var2 and var3 is and check is var1 is bigger than that? If that returns true you already know it's bigger than both. (e: that's one way at least, might not be the best.)
Upvotes: 1
Reputation: 1193
Yuo can check like this:
e = (var1 > var2 ) || (var1 > var3) && (var1 < var2) + var3;
Upvotes: 0
Reputation: 12523
try this:
if (var1 > var2 ||var1 > var3 && !(var1 < (var2 + var3) )){
Assert.assertTrue(true);
}
Upvotes: 0
Reputation: 135
XOR is not out of the box in java you should test both case if((x1>x2 && x1<xx3)||(x1<x2 && x1>x3))
Upvotes: 0