+ 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

25th Feb 2017, 8:19 PM
Beta Bet
Beta Bet - avatar
7 Respostas
+ 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.
25th Feb 2017, 8:24 PM
J.G.
J.G. - avatar
+ 5
Yeah, works. Inspired me to code something... Examples for the logical operators: https://code.sololearn.com/cnMMk8BODddd/?ref=app
25th Feb 2017, 8:54 PM
Tashi N
Tashi N - avatar
+ 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
25th Feb 2017, 9:43 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
@ChaoticDawg thanks for the explanation, that is exactly the information I was looking for
25th Feb 2017, 10:09 PM
Beta Bet
Beta Bet - avatar
+ 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 }
25th Feb 2017, 11:17 PM
Beta Bet
Beta Bet - avatar
0
I believe it is, I'm pretty knew to coding but I believe it is possible
25th Feb 2017, 8:25 PM
Trey Sarver
Trey Sarver - avatar
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
25th Feb 2017, 8:32 PM
Beta Bet
Beta Bet - avatar