Or operand not working in while loop [duplicate] - java

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!");

Related

Adding a condition to if statement if another condition is true

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))

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

How do I only allow numbers in a JTextField using a KeyEvent?

My attempt at this is:
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar();
if(c != '1' && c != '2' && c != '3' && c != '4'
&& c != '5' && c != '6' && c != '7' && c != '8'
&& c != '9' && c != '0') {
evt.consume();
}
Which is quite strange, since this is what my book has shown me.
Also, is this viable in comparison to a Formatted Text Field?
You should never use KeyListeners with text components
For one, it doesn't take into account what happens when the user pastes text into the field. It's also possible that the key event could be consumed and never reach your listener
Swing has a number of components which might fulfill your needs
JSpinner
JFormattedTextField
Both these are capable of restricting user input to numbers and I'm the case of the JSpinner, ranges of numbers
These fields are post processing, that is, they will allow the user to enter what ever they want, but will validate the value when the loses focus or the user accepts the value
If you want real time filtering you should use a DocumentFilter, for examples
Try replacing your if (Mile of tests) with:
if(c < '0' || c > '9')
evt.consume();
or, the more readable, as azurefrog pointed out:
if(!Character.isDigit(c))
evt.consume();
If you want the backspace and delete button to function then you need to put them inside your if statement
sample:
if(c != '1' && c != '2' && c != '3' && c != '4'
&& c != '5' && c != '6' && c != '7' && c != '8'
&& c != '9' && c != '0') || !(c == KeyEvent.VK_BACK_SPACE) ||
!(c == KeyEvent.VK_DELETE)){
evt.consume();
}

How to check if a character is correct

I have a bunch of characters and want to remove everything that isn't a '#' '.' 'E' and 'G'.
I tried to use this:
if (buffer.get(buffertest) == 'G'|'E'|'#'|'.')
But got an issue with an incompatible type.
This root problem is incorrect use of the bitwise OR operator, and the Java operator precedence hierarchy. Java expressions of this type are evaluated left to right, and the == operator takes precedence over |. Which when combined, your expression roughly translates to:
(buffer.get(buffertest) == 'G') | 'E' | '#' | '.'
The first part of the expression buffer.get(buffertest) == 'G' evaluates to a boolean.<br>
The second part of the expression'E' | '#' | '.'` evaluates to an int, which is narrowed to a char
Which leads to an incompatible type compile time error. You can correct your code by expanding the check this way:
char ch = buffer.get(buffertest);
if(ch == 'G' || ch == 'E' || ch == '#' || ch == '.') {
// do something
}
You need to compare for each character individually. Assuming that buffer.get(buffertest) returns a char, here's how to do it:
char c = buffer.get(buffertest);
if (c == 'G' || c == 'E' || c == '#' || c == '.') {
// do something
}
Alternatively, you could do something like this:
char c = buffer.get(buffertest);
if ("GE#.".contains(Character.toString(c))) {
// do something
}
You haven't shown the type of buffer, which makes things harder. But assuming buffer.get returns a char, you could use:
if ("GE#.".indexOf(buffer.get(buffertest) >= 0)
Or you could check each option explicitly, as per Simulant's answer... or to do the same thing but only calling get once:
char x = buffer.get(buffertest);
if (x == 'G' || x == 'E' || x == '#' || x == '.')
Your original code is failing because | is trying to perform a bitwise "OR" operation on the four characters... it's not the same thing as performing a logical "OR" on four conditions.
if (buffer.get(buffertest) == 'G'||
buffer.get(buffertest) == 'E'||
buffer.get(buffertest) == '#'||
buffer.get(buffertest) == '.')

Categories

Resources