+ 1
Is it possible to use logical XOR operator in multiple condition statement in java?
Ex. if (Bool1 ^ Bool2 ^ Bool3 ^ Bool4) { \\ Do something } It should execute only if exactly one of the conditions is met
7 Answers
+ 5
I believe it should work. You can do this:
if (a==b || c==d || e==f){
//code
}
Using bitwise operators, I think it should also work.
I don't know the context of it, though.
+ 5
Yeah, works. Inspired me to code something...
Examples for the logical operators:
https://code.sololearn.com/cnMMk8BODddd/?ref=app
+ 1
if (Bool1 ^ Bool2 ^ Bool3 ^ Bool4)
This won't work the way you're asking. It will return true if an odd number of booleans are true, false otherwise. As you're basically just flipping bits 0 and 1.
Where 0 = false and 1 = true.
1 ^ 0 = 1
1 ^ 1 = 0
0 ^ 1 = 1
0 ^ 0 = 0
1 ^ 0 ^ 0 ^ 0 = 1 true
1 ^ 1 ^ 0 ^ 0 = 0 false
1 ^ 1 ^ 1 ^ 0 = 1 true
@J.G.
if (a==b || c==d || e==f)
This won't work either as it will return true if any 1 or more are true.
You will need to be explicit in what your looking for in order to get the correct result. You should break them into multiple if statements for easier implementation and understanding.
Check if bool1 is true and all others are false!
if((bool1 && !bool2 && !bool3 && !bool4) && bool1)
The first section will return true if only bool1 is true or if bool1 is false and all others are true. This is why we also check for bool1 by itself to be true.
You can do a similar if statement for each other individual boolean. There may be a better way to do it, but I'm tired and my thinker is giving up on me right now. lol
+ 1
@ChaoticDawg thanks for the explanation, that is exactly the information I was looking for
+ 1
Here is the shortest way I found around if it may help anyone facing the same problem :
If ((Bool1 ? 1 : 0) + (Bool2 ? 1 : 0) + (Bool3 ? 1 : 0) + (Bool4 ? 1 : 0) == 1)
{
// Whatever
}
0
I believe it is, I'm pretty knew to coding but I believe it is possible
0
@J.G. This would work if multiple conditions are met, I need to have exclusively one for the code to execute, else it needs to remain inactive