Adding a condition to if statement if another condition is true - java

Is it possible to add a condition in if statement if a certain condition is true?
For example,
I have this variable,
private Boolean doesExist
if doesExist is set to True then I want my if statement like this,
if (A == B && B == C)
if doesExist is set to False then I don't want the second condition in my if condition,
if (A == B)

How about something like this?
if ((doesExist && (A == B && B == C)) || (!doesExist && A == B)) {
// Do stuff
}
When doesExist is true, the predicate depends on (A == B && B == C) (left side of the 'or' operator); when doesExist is false, the predicate depends on A == B (right side of 'or' operator.
Even more sucinct, what about:
if(A == B && (!doesExist || B == C)) {
// do stuff
}
In this case, the value of B == C only affects the overall value of the predicate when doesExist is True.

if (A == B && (!doesExist || B == C))

You can just go with
if(doesExist ? (A == B && B == C) : (A == B))

If the A == B condition will change, then we need update it in two places in suggested solutions, I think better would be to always test A == B and conditionally test second one like:
if(A == B && (!test || B == C))

Related

Or operand not working in while loop [duplicate]

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 4 years ago.
I have this loop statement, which I'll express using C-like syntax (C, C++, Java, JavaScript, PHP, etc. all use similar syntax):
while (c != 'o' || c != 'x') {
c = getANewValue();
}
I want it to run until I get a 'o' or 'x', but it never exits, even when c is 'o' or 'x'. Why not?
I've also tried using if:
if (c != 'o' || c != 'x') {
// Show an error saying it must be either 'o' or 'x'
}
but that also always shows the error message, even when c is 'o' or 'x'. Why?
The condition (c != 'o' || c != 'x') can never be false. If c is 'o', then c != 'x' will be true and the OR condition is satisfied. If c is 'x', then c != 'o' will be true and the OR condition is satisfied.
You want && (AND), not || (OR):
while (c != 'o' && c != 'x') {
// ...
}
"While c is NOT 'o' AND c is NOT `'x'..." (e.g., it's neither of them).
Or use De Morgan's law, covered here:
while (!(c == 'o' || c == 'x')) {
// ...
}
"While it's NOT true that (c is 'o' or c is 'x')..."
It must be if(c!='o' && c!='x') instead of if(c!='o' || c!='x'). If you use the or operator the boolean expression will be always true.
Why is my c != 'o' || c != 'x' condition always true?
The expression combines two sub-expressions using the logical OR operator (||). The expression is true if at least one of the sub-expressions is true. In order to be false, both sub-expressions it connects must be false.
The sub-expressions are c != 'o' and c != 'x'.
The first sub-expression c != 'o' is false when c == 'o'. The same for the second one; it is false when c == 'x'.
Please note that they cannot be false on the same time because c cannot be 'o' and 'x' on the same time.
The condition should be if(!(c=='o' || c=='x')) or if(c!='o' && c!='x')
even when you enter x or you enter o in that case if condition evaluates to true and hence game_start remains false.
it should be if(c!='o' && c!='x')
or use a more straight forward way
if(c == 'o' || c == 'x')
game_start=true;
else
System.out.println("you can only enter o or x!");

How to check if all boolean are true or false in Java?

I'm trying to figure out how to check if three variables are all true or all false. So that the condition becomes true, when these variables have the same value and false, when they don't have the same value.
I thought something like (d == e == f) would help me here but the condition is only true when all variables are set to true. But when they're set to false, the condition doesn't work. Could anyone explain to me why? I know a very basic issue but I really can't figure it out myself.
You can try like this :
if((d && e && f) || (!d && !e && !f))
It will enter in loop either all will be true or all will be false.
It's because all expressions having relational operators return Boolean value.
So, first e == f is evaluated. As these both are false (both operators having same value) so, this expression return true value.
This true value is evaluated against d which is false. So that expression returns false (as both Operators have different values now) .
To know if the 3 variables are all true or all false; this what you can do:
boolean allTrue, allFalse;
if(a && b && c) allTrue = true; //a, b & c will evaluate to boolean and if all three vars are true the condition will be true and hence the if statement will be accessed
if(!a && !b && !c) allFalse = true; //if the not of the 3 is true, i.e (the 3 boolean vars are false), the whole condtion will be true and the if-statement will be accessed and the allFalse will be set to true means all 3 are false
boolean allTrue=false;
boolean allFalse=false;
boolean a,b,c;//your three variables
if(a && b && c)
{allTrue=true;}
else if(!a && !b && !c)
{allFalse=true;}
Try this, here i have two variable flags that are set to false initially, when one of the condition is true then only it woll be set to true so after the last line of code you can check if allFalse or allTrue has values true or false.
It should be possible to stay closer to the original formulation like this:
boolean eitherAllTrueOrAllFalse = (d == e) && (d == f)
If you only need to know if all are true or all false, then this will be more than enough:
boolean flagAllTrue = a && b && c;
No need to use a if else.
First think of the conditions separately:
boolean allTrue = a && b && c;
boolean allFalse = !(a||b||c);
Then combine them:
boolean eitherAllTrueOrAllFalse = allTrue|allFalse;
let sum = 0;
sum += a ? 1:0; sum += b ? 1:0; sum += c ? 1:0;
let allTrueOrAllFalse = ( sum === 0 || sum === 3 );

If with multiple &&, || conditions Evaluation in java

if(a && b || c || d || e)
whether it check (a && b), if a and b must be true always, then only allow inside ? or
((a && b) || a && c || a && d || a && e)), any of the condition is true will it allow inside ?
If I understand you correctly, in the first part of your question, you are asking whether a and b must both be true for the entire expression (a && b || c || d || e) to evaluate as true.
The answer to that question is no. Java operators are such that && has higher precedence than ||. So the equivalent expression is:
(a && b) || c || d || e
Therefore the expression as a whole will evaluate to true if any of a && b or c or d or e is true. For example, if a was false and c was true, the expression as a whole is true.
Note that Java conditional operators short-circuit. This means that once the end result of the expression is known, evaluation stops. For example, if a and b were both true, meaning the overall expression must evaluate to true, then c, d and e are not evaluated.
For the second part of your question, we can apply the same logic. The equivalent expression is therefore:
(a && b) || (a && c) || (a && d) || (a && e)
This will evaluate to true if any of the sub-components, eg. a && c evaluates to true. As others have noted, a must be true for the expression to be true as it is part of every sub-component. Then if any of the other variables is true, the expression is true.
Once you understand that, you can see how the simplification of this expression suggested by #Arc676 is arrived at:
a && (b || c || d || e)
I should also add that the two expressions in your question are different logically. They are equivalent to:
(a && b) || c || d || e
and
a && (b || c || d || e)
The parentheses affect the order of evaluation. In the first, a and b are grouped together by an &&, hence both must be true for that part of the expression (in the parentheses) to be true. In the second, b, c, d and e are grouped together by ||. In this case, only one of b, c, d and e needs to be true for that part of the expression (in the parentheses) to be true.
Dave's answer is pretty good. Look there for an explanation.
If you are still having trouble I'll simplify it.
Case 1:
if(a && b || c || d || e)
In this case you can simplify it by saying z = a && b
This means that the expression becomes
if(z || c || d || e)
This is the same as the expression above. z is only true if a and b are true.
Case 2:
((a && b) || a && c || a && d || a && e))
As Arc676 commented, you can simplify it as
a && (b || c || d || e)
Here you can use the same technique as in case 1 to further simplify it.
If you take y = b || c || d || e. Meaning y is true if any of b, c, d or e are true. Then you can simplify the expression as
a && y
I'm not saying you should always simplify this but using this technique can make long boolean statements more readable.
if this is a part of a big code then you'll have to simplify the condition such that the processor will process fast in order to give you an accurate compilation in lesser time.
the most appropriate condition according to me can be " a && (b|| c|| d|| e) " so by using such condition it will just do it in one step rather than going into every condition calling "a" everytime....
for more help you can check on this link and also helps me a lot... Hope you'll get your answer : " http://www.homeandlearn.co.uk/java/java_if_else_statements.html " .
((a && b) || (a && c) || (a && d) || (a && e))
in this one, a has to always be true and either b, c, d, or e has to be true to go in.
if(a && b || c || d || e)
in this one, a and b have to be true, other wise only c or only d or only e have to be true.
in the snippet it shows that a and b have to be true. if a and b are not true then it can go check if c or d or e are true then it will still be true.
function test(a, b, c, d, e) {
if ((a && b || c || d || e)) {
return a;
}
}
document.getElementById("demo1").innerHTML = " a = 1, b = 0, c = 0, d = 0, e = 0 answer: " + test(1, 0, 0, 0, 0);
document.getElementById("demo2").innerHTML = " a = 0, b = 1, c = 0, d = 0, e = 0 answer: " + test(0, 1, 0, 0, 0);
document.getElementById("demo3").innerHTML = " a = 1, b = 1, c = 0, d = 0, e = 0 answer: " + test(1, 1, 0, 0, 0);
document.getElementById("demo4").innerHTML = " a = 0, b = 0, c = 1, d = 0, e = 0 answer: " + test(0, 0, 1, 0, 0);
<h1>JavaScript Variables</h1>
<p>In this example, a, b, c, d and e are variables</p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
if(a && b || c || d || e) can be evaluated as both 1 and 2 below :
1 -> if ( a && ( b || c || d || e) )
2 -> if ( (a && b) || (a && c) || (a && d) || (a && e))
Conclusion will be as below :
statement will be true when --> a is true and anyone of b or c or d or e is true
if(a && b || c || d || e) stands for:
If a is true and b or c or d or e is true then it will go inside. That's it.
So, if a is true and at least any rest other variables(b or c or d or e) then it will go inside. Otherwise it won't.

Logic evaluation with && and || in a statement

I'm just debugging some code and found some expression:
if (mObject != null && a || b )
{
mObject.someMethod();
}
which had a NullPointerException in the mObject.someMethod() line - so my question is:
how is the expression evaluated?
1. a && b || c == a && (b || c)
or
2. a && b || c == (a && b) || c
If 1. is the case i'd probably have to look at some multithreading issues.
This is probably a dumb question and i'm pretty sure it has been asked before, but i can't find the answer here. Thanks for the answers in advance.
It is equivalent to the following condition:
if ((mObject != null && a) || b )
&& has a higher precedence that ||.
If mObject is null, the condition may pass if b is true.
!= has precedence over && which has precedence over || (Source)
Therefore
if (mObject != null && a || b )
is equivalent to
if (((mObject != null) && a) || b )
To avoid the exception, use parentheses :
if (mObject != null && (a || b) )
According to here, it's:
((( mObject != null ) && a ) || b )
so you should be looking into b, because:
(null != null) is false
false && a is always false
everything depends on b then.
If parentheses are not provided then it will be always evaluated from left to right of the equals expression.

operator precedence && and ||

please ignore the question - its wrong
I am not sure if my question is issue is related to operator precedence- Just to rule out that I added additional bracket. My understanding is in that case that code in each bracket will be executed. So basically all the OR operation will happen and its output would be AND'ed to condition a.
I have below set of parameters a = true and c = 254 , b is not availble ( b is initialized to 0 -At any given time either b or c only is availble) . So for the above condition I am expecting if condition to result in true but it's resulting in false condition. Any reason why ? Also what is best way to debug such things as in where exactly condition is going wrong - any pointers
if ((a == true) && ((b == 460) || (b == 454) || (b == 455) ||
(c> 13568 && c< 14335) ||
(c> 10640 && c< 10655) ||
(c> 11296 && c< 11311) ||
(c> 25600 && c< 26111) || (c== 7825)))
First a is evaluated, if (a == true) evaluated to true, then only it will execute next && statement
((b == 460) || (b == 454) || (b == 455) ||
(c> 13568 && c< 14335) ||
(c> 10640 && c< 10655) ||
(c> 11296 && c< 11311) ||
(c> 25600 && c< 26111) || (c== 7825))
Inside this, it will check for any one condition which is true, and once it encounter any one statement true, it return from there.
For your condition to be true, a must be true, and in addition, at least one of the conditions on b or c must be true.
Therefore, if a==true and c==254, you will get false, since c is not within any of the ranges you allow, and, as you said, b is not available (which I'm assuming means it doesn't have one of the 3 values you allow).
It would be much simpler if the code is written in a more readable manner;
bool isEqualToAny(int valueToCheck, int[] listToCheckIn){
boolean isMatch = false;
(for item in listToCheckIn){
if (item == valueToCheck){
isMatch = true;
break;
}
}
}
bool isWithinRange(int valueToCheck, int min, int max){
return (valueToCheck > min && valueToCheck < max);
}
if ((a == true)
&& (isEqualToAny(b, int[]{460,454,455})
|| isWithinRange(c,3568,14335)
|| isWithinRange(c,10640,10655)
|| isWithinRange(c,11296,11311)
|| isWithinRange(c,25600,26111)
|| isWithinRange(c,10640,10655)
|| (c== 7825)))
In java8 you can use an array of Tuples to make #isWithinRange more like #isEqualToAny

Categories

Resources