Do loop while input isn't a or b? - java

I'm doing the finishing touches for a class project and I'm adding in a safety net for one of my user inputs. I have it set so that if the user puts in "1" or "2", the data they enter will be displayed in different ways. I want to add a method that prevents the user from entering anything other than "1" or "2". Here is the code for it.
do
{
System.out.println("Please type either '1' or '2'.");
Scanner scan = new Scanner(System.in);
a = scan.nextInt();
}
while (a != (1||2));
//after user enters 1 or 2, return the choice
return a;
I've been reading about the operands and logic, but I'm kind of stuck. I've been badgering my teacher the whole way through so I figured I'd give him a break since I'm not his only student. My error is saying "bad operand types for binary operator '||'.

This is a common misconception when learning programming.
You, as a human, can easily read the statement which reads like this: "while a is not 1 or 2", but the computer has to follow certain rules, and one of the rules is that "or" takes precedence.
What this means is that it first triest to figure out what "1 or 2" means, since basically, your statement is similar to this:
while (a != SOMETHING);
|| in the Java language is "logical or", which translates to this: Take the two values (called operands) on each side of the || (called the operator), and combine them according to the rules of "logical or".
"logical or" uses two boolean values, which can only be True or False, and since you asked it to use the operator with numbers, that's why you get that particular error message.
If you had tried using the single pipe, |, the compiler might have stopped complaining, but it would still not do what you want it to do.
1 or 2 when dealing with numbers, using the | operator, which is the "bitwise or" operators, you would get the two numbers combined to form the number 3. You can read more about "bitwise operators" if you want to know why.
In short, you cannot write your comparison like this.
In programming languages, comparisons are done two values at a time, ie. one against another, so your only choice is to expand the expression to compare twice.
Here is some equivalent expressions which will give you what you want:
while (a != 1 && a != 2);
or this:
while (!(a == 1 || a == 2));
To be hones, I like the first better.

It is (a != 1 && a!=2) - You actually want to exit the loop when a is either 1 or 2.

You need to do separate conditional statements for a!= 1 and a!= 2.
Your conditional statement should look something like this:
(a!=1) && (a!=2)

You can't treat an int like pseudo-regex. Replace
while (a != (1||2));
with
while (a != 1 && a!= 2);

try this in your while loop condition
((a!=1) && (a!=2))

You have to write
while (a != 1 && a != 2)
because it's the equivalent of not (a == 1 || a == 2)

The binary operator '||' needs two boolean operand on both side. Since, your operands are integers, this is a syntax error.
You should do it in this way:
do{
// core of the loop...
}while(a!=1 && a!=2);

The problem here is you are trying to write code that makes sense read as English, but it doesn't work like that. The || operator takes two expressions and returns if one or the other is true. That means what you have written doesn't make sense.
The simplest way to replace this is to expand it out:
a != 1 && a != 2
(We need to use && as we are checking that neither of them is true).
Note that this can become verbose and awkward. Alternatively, a good replacement (given you have a lot of values to check) is a membership check in a collection (a Set is a good choice as you are guaranteed a O(1) membership test). E.g:
Set<Integer> possibles = new HashSet<Integer>();
Collections.addAll(possibles, new Integer[] {1, 2, ...});
while (!possibles.contains(a)) {
...

Related

If statement and && gives IDE error 'Syntax error on token "=", <= expected'

I have a simple guess number game. It has a function to ask whether you want tips. It saves the response in a boolean called tips as shown.
while (run) {
while (tinvalidrun){
System.out.println("Do you want any tips? y or n?");
input=in.next();
switch(input){
case "y":
System.out.println("Ok, we will tell you how close you are!");
tinvalidrun=false;
tips=true;
break;
case "n":
System.out.println("Wanna go hard eh? Well, go along!");
tinvalidrun=false;
break;
default:
System.out.println("You pressed the wrong key!\nDo you have butter fingers?");
}
}
Then I have some more code that makes more variables and makes a random number. And finally I get the user input for the guess and test it:
do {
System.out.println("Enter a number: ");
guess = in.nextByte();
times++;
if (guess == gval) {
break;
} else {
System.out.println("No luck! Try again!");
if (tips=true) {
if (guess < gval) {
System.out.println("You are too low!");
}
else {
System.out.println("You are too high!");
}
}
}
I tried putting the tips=true and guess < gval in one if with && but it doesn't work. I did this:
if(guess<gval && tips=true)
It asks me to replace = with <= or something like that. I tried using two if statements but when you say no, it still shows the tips. I tried looking at the brackets but they look fine. Please Help! If there is any simplification or improvements or ideas I can do to my code, they are welcome.
I have more question as well. It crashes (obviously) when you try to type a letter to the integer. I tried using strings and my tinvalidrun loop to avoid this but I can't. Is there a way to do this?
Thanks! :)
Testing equality
You need tips == true, or just if (guess<gval && tips) and if (tips) as you are testing a boolean.
= is an assignment operator, == is an equality operator. It is easy to mix the two up, but the difference is enormous...
Boolean assignment is also an (unexpected) equality test
You say "I tried using two if statements but when you say no, it still shows the tips.". The if statement expects an expression which must have type boolean. Any assignment expression (i.e. tips = true) evaluates as the new value assigned to the variable. From the JLS §15.26.1 Simple Assignment Operator:
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.
Therefore if (tips = true) is valid syntax, because tips = true is both an assignment and also a boolean expression which can therefore be used in an if.
In your case tips = true assigns true to tips (even if it started out false), then returns that new value of tips. The if sees the new value (true) and continues happily on. It is not therefore a test that tips was originally true. By example, this means that the following prints out the "Oops!" text:
boolean tips = false;
if (tips=true){
System.out.println("Oops! This tests as true, but that isn't what we wanted");
}
As you can see, conflating assignment and testing is generally a bad idea. It is usually a mistake if you use = in an if/do/while expression. Sometimes it can help with brevity but it is generally bad practice.
Why doesn't if (guess<gval && tips = true) work?
This is due to operator precedence. In the expression if (guess<gval && tips = true) the operator precedence is < then && and then =, so the compiler no longer evaluates the tips = true part as an assignment of true to tips. You could use brackets to contain tips = true, but as I said above you don't really want the assignment so you can ignore this detail †.
Testing valid byte input
For the last part of your question - you say you get an invalid byte if someone inputs a letter. I'm guessing you get a java.util.InputMismatchException.
You can use Scanner.hasNextByte() to test if the input is a byte before consuming it. If that returns false you can consume and discard the input using nextLine(), print out an error message and loop again.
† Depending on how you were writing your code you may also have seen a message from eclipse such as "The operator <= is undefined for the argument type(s) boolean, Boolean" or from javac such as "error: unexpected type ... required: variable, found: value". None of them tell you much other than your syntax is sufficiently messed up the compiler can't parse it.
if(tips = true) is always true condition because here we have assigned value true to tips.
It will first assign tips to true and then check will be performed in if so your else part is dead due to this code and control will never ever enter in else part.
If you want to check whether tips is true or not then you can just write if(tips) and if you want to check whether it is false than you should write if(tips == false). Where == will check equality while = will assign the value or reference.
Firstly, the test for equality operator is == not =. Secondly, you don't need the operator when testing a boolean. if (tips) ... is enough.
= and == are two completely different things. = is the assignment operator and is used to assign values to variables. == is the equality operator and is used to check if a variable is equal to a certain value, or equal to another variable.
You should be using == instead.
In this line
if(tips=true)
single = means assigning
This should be
if(tips==true)
One equal sign is for assigning as you have done in (guess = in.nextByte();, tinvalidrun=false, tips=true;, and so..) the value in the RHS variable is "put" to the LHS variable. The become equal, i.e they contains the same value. To compare, use two equals sign operator,comparison operator (foo1 == foo2). several operators
There is a little change, use == instead of =
Instead of
if (tips=true)
you would have do
if (tips==true)
Comparison is double ==, single is assignment.
comparison with true is redundancy (but legal)
if(guess < gval && tips==true)
or
if(guess<gval && tips)
Your code fragment doesn't show variable declarations, maybe you compare wrong types too. My fragments assume that tips is boolean.

JAVA looping logic error with NOT .equalsIgnoreCase()

I'm trying to use equalsIgnoreCase() in a while loop to try and check if something other than what was intended to be written was written by using the NOT (!) operator. For example:
String temp="A";
boolean x =(!temp.equalsIgnoreCase("a")) ;
See, this works with a while loop. If it's not A, it will keep looping but this next line does not
boolean x =(!temp.equalsIgnoreCase("a") || !temp.equalsIgnoreCase("b")) ;
This does not seem to work anymore. This returns true, no matter what you type, even if it is a or b. So when I use the whole line of code to check for any of the letters that are not suppose to be used:
while (!temp.equalsIgnoreCase("A") || !(temp.equalsIgnoreCase("B")) ||!temp.equalsIgnoreCase("D")|| !temp.equalsIgnoreCase("P") || !temp.equalsIgnoreCase("S"))
{ ***Do Code***}
it loops whatever you put in, even if it will equal one of the letters.
When there is more than one !temp.equalsIngnoreCase, the code does't work with OR (||).
The only way I can get it to work is if I change the OR to AND
while (!temp.equalsIgnoreCase("A") && !(temp.equalsIgnoreCase("B")) && !temp.equalsIgnoreCase("D")&& !temp.equalsIgnoreCase("P") && !temp.equalsIgnoreCase("S"))
Even though I seem to have found a solution, I still don't understand why OR doesn't work but AND does. I removed the NOT to see if everything works, and it seems to loop perfectly when one of the letters is entered.
it loops whatever you put in, even if it will equal one of the letters.
Yes, of course it does.
You're asking it to keep going while it isn't A or it isn't B. Well nothing can be both A and B... if the value is equal to B then it won't be equal to A so the first operand will keep the loop going. If the value is equal to A then it won't be equal to B so the second operand will keep the loop going.
Your solution of changing to AND is correct - you want the value to not be A and not be B (i.e. it's neither A nor B).
Alternatively, you could use OR internally, but put a NOT around the whole thing:
while (! (temp.equalsIgnoredCase("A") || temp.equalsIgnoreCase("B") || ...))
I still don't understand why OR doesn't work but AND does
The expression using || will always be true at any given value of temp. Because, temp cannot be both a and b at the same time. If it is a, then the 2nd part of || will be true, and if it is equal to b or any other value, the first part will be true, thus making the entire expression true in both the cases.
With &&, your while will only be true, if temp is neither of a nor b.
Alternatively, if you are going to test temp against many values, you can change your while condition to look simpler:
while (!"ABDPS".contains(temp.toUpperCase())) {
}
its a foul logic. the code
(!temp.equalsIgnoreCase("A") || !(temp.equalsIgnoreCase("B")) ||!temp.equalsIgnoreCase("D")|| !temp.equalsIgnoreCase("P") || !temp.equalsIgnoreCase("S"))
means
if char is not A, or not B, or not D, or not P, or not S. It will always evaluate to true, since is char is A, it will neither be B,D,S nor P. so is for the others.
if you want it to be OR logic, it should be:
(!(temp.equalsIgnoreCase("A") || (temp.equalsIgnoreCase("B")) ||temp.equalsIgnoreCase("D")|| temp.equalsIgnoreCase("P") || temp.equalsIgnoreCase("S")))
which means, not when the char is either of A, B, D,S or P
This is all about logic.
A OR B means that is is true when A is true or B is true or both are true.
In your special case it is only possible that one of your equalsIgnorecase() can ever work, so you wrote something like a tautology which means an endless loop.
You can read about boole algebra here: http://en.wikipedia.org/wiki/Boolean_algebra_%28structure%29
Kind of some theory but it explains what you need to know when you write boolean expressions.
Hope this helps :)

Should I separate AND with two if statements?

I have the following lines in my code:
if (command.equals("sort") && args.length == 2) {
//run some program
}
Someone suggests that I should use two separate if statements because there's no need to evaluate any of the other if statements if the command does not equal to "sort"​, regardless of whether or not the args length is correct.
So according to that that, I need to rewrite my code to:
if (command.equals("sort")) {
if (args.length == 2) {
//run some program
}
}
I know they both do the job, but my question is which one is better and more efficient?
No, that's not true. They call it short circuit, if the first condition evaluates as false, the second one would not be evaluated at all.
Well, since && is a short-circuit operator. So both the if statements are effectively the same.
So, in first case, if your command.equals("sort"), returns false, the following condition will not be evaluated at all. So, in my opinion, just go with the first one. It's clearer.
As stated, short circuit will cause the program to exit the if statement the moment a condition fails, meaning any further conditions will not be evaluated, so there's no real difference in the way the two formats are evaluated.
I would like to note that code legibility is negatively affected when you have several if statements nested within each other, and that to me is the main reason not to nest. For example:
if( conditionA && conditionaB && !conditionC ){
// Do Something
}
is much cleaner than:
if( conditionA ){
if( conditionB ){
if( !conditionC ){
// Do Something
}
}
}
Imagine that with 20 nested if statements? Not a common occurrence, sure, but possible.
They are the same. For your first example, any modern runtime will ignore the second expression if the first expression is false.
short circuiting is better which is done by && if you are check null case for a value and then apply a function on that object, short circuit operator works well. It stops from condition 2 to be executed if condition 1 is false.
ex:
String s=null;
if(s!=null && s.length())
This doesnt throw exceptions and also in most cases you save one more if check.
If the conditions are in the same order, they are exactly the same in terms of efficient.
if (command.equals("sort") && args.length == 2)
Will drop out if command.squals("sort") returns false and args.length will never be checked. That's the short-circuit operation of the && operator.
What it comes down to is a matter of style and readability. IMO When you start chaining too many together in a single if statement it can get hard to read.
Actually, it is called [Lazy_evaluation]: http://en.wikipedia.org/wiki/Lazy_evaluation
That's not really the question but note that if you want the two if evaluated, you can use & :
if (methodA() & methodB()) {
//
}
instead of
boolean a = methodA();
boolean b = methodB();
if (a && b) {
//
}
yeah, their suggestions are completely right. What I suggest you is to write the first check as:
"sort".equals(command)
Maybe it does not make sense in this case but in future. Use the static type first so you never need a null check before

What is better: multiple "if" statements or one "if" with multiple conditions?

For my work I have to develop a small Java application that parses very large XML files (~300k lines) to select very specific data (using Pattern), so I'm trying to optimize it a little. I was wondering what was better between these 2 snippets:
if (boolean_condition && matcher.find(string)) {
...
}
OR
if (boolean_condition) {
if (matcher.find(string)) {
...
}
}
Other details:
These if statements are executed on each iteration inside a loop (~20k iterations)
The boolean_condition is a boolean calculated on each iteration using an external function
If the boolean is set to false, I don't need to test the regular expression for matches
Thanks for your help.
One golden rule I follow is to "Avoid Nesting" as much as I can. But if it is at the cost of making my single if condition too complex, I don't mind nesting it out.
Besides you're using the short-circuit && operator. So if the boolean is false, it won't even try matching!
So,
if (boolean_condition && matcher.find(string)) {
...
}
is the way to go!
The following two methods:
public void oneIf(boolean a, boolean b)
{
if (a && b)
{
}
}
public void twoIfs(boolean a, boolean b)
{
if (a)
{
if (b)
{
}
}
}
produce the exact same byte code for the method body so there won't be any performance difference meaning it is purely a stylistic matter which you use (personally I prefer the first style).
Both ways are OK, and the second condition won't be tested if the first one is false.
Use the one that makes the code the more readable and understandable. For just two conditions, the first way is more logical and readable. It might not be the case anymore with 5 or 6 conditions linked with &&, || and !.
I recommend extracting your expression to a semantically meaningful variable and then passing that to your evaluation. Instead of:
if (boolean_condition && matcher.find(string)) { ... }
Assign the expression to a variable, then evaluate the variable:
const hasItem = boolean_condition && matcher.find(string)
if (hasItem) { ... }
With this method, you can keep even the most complex evaluations readable:
const hasItem = boolean_condition && matcher.find(string)
const hasOtherThing = boolean_condition || boolean_condition
const isBeforeToday = new Date(string) < new Date()
if (hasItem && hasOtherThing && isBeforeToday) { ... }
Java uses short-circuiting for those boolean operators, so both variations are functionally identical. Therefore, if the boolean_condition is false, it will not continue on to the matching
Ultimately, it comes down to which you find easier to read and debug, but deep nesting can become unwieldy if you end up with a massive amount of braces at the end
One way you can improve the readability, should the condition become longer is to simply split it onto multiple lines:
if(boolean_condition &&
matcher.find(string))
{
...
}
The only choice at that point is whether to put the && and || at the end of the previous line, or the start of the current.
I tend to see too many && and || strung together into a logic soup and are often the source of subtle bugs.
It is too easy to just add another && or || to what you think is the right spot and break existing logic.
Because of this as a general rule i try not to use either of them to avoid the temptation of adding more as requirements change.
If you like to be compliant to Sonar rule squid:S1066 you should collapse if statements to avoid warning since it states:
Collapsible "if" statements should be merged
The first one. I try to avoid if nesting like that, i think it's poor style/ugly code and the && will shortcircuit and only test with matcher.find() if the boolean is true.
In terms of performance, they're the same.
But even if they weren't
what's almost certain to dominate the time in this code is matcher.find(string) because it's a function call.
Most would prefer to use the below one, because of "&&".
if (boolean_condition && matcher.find(string)) {
...
}
We normally called these as "short-circuit (or minimum evaluation)". It means the 2nd argument (here it is "matcher.find(string)") is only evaluated only if the 1st argument doesn't have sufficient information to determine the value of the expression. As an example, if the "boolean_condition" is false, then the overall condition must be false (because of here logical AND operator). Then compiler won't check the 2nd argument which will cause to reduce the running time of your code.

Does Java check all arguments in "&&" (and) operator even if one of them is false?

I have such code:
if(object != null && object.field != null){
object.field = "foo";
}
Assume that object is null.
Does this code result in nullPointerException or just if statement won't be executed?
If it does, how to refactor this code to be more elegant (if it is possible of course)?
&& does short circuit while & would not.
But with simple questions like this, it is best to just try it (ideone can help when you don't have access to a machine).
&& - http://ideone.com/LvV6w
& - http://ideone.com/X5PdU
Finally the place to check for sure would be the JLS §15.23. Not the most easy thing to read, the relevent section states:
The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
Java does have short circuit evaluation, i.e. your code should be ok
One way to know it! Test it! How? Well, make a method which prints out something:
public static boolean test(int i)
{
System.out.println(i);
return false;
}
...
if (test(1) && test(2) && test(3))
{
// not reached
}
This prints:
1
So the answer on your question is "no".
Best way to find out would be try it, especially for a single line question. Would have been faster, too.
The answer is that Java will not execute the body of the "if".
This will not throw any NullPointerException . The condition will be evaluated from left to right and the moment first false expression is found it will not evaluate remaining expression.
Maybe this other question helps you:
Differences in boolean operators: & vs && and | vs ||
Java has short circuit evaluation, so it will be fine.
The code looks ok to me, but do you actually need to check object.field != null? I think that test can be omitted as you never use the variable, just set it.
On a side-note, most programmers wouldn't access fields directly (object.field) but rather through getters/setters (object.setField(x);). Without any more context to go on, I can't say if this is appropriate in your case.
&& and || conditions stops at the point they can decide whether the condition is true/false, in your case, the condition will stop right after object != null and I think that your code is just fine for this case
If you want all of your boolean expressions evaluated regardless of the truth value of each, then you can use & and | instead of && and ||. However make sure you use these only on boolean expressions. Unlike && and ||, & and | also have a meaning for numeric types which is completely different from their meaning for booleans.
http://ibiblio.org/java/course/week2/46.html
Although short circuiting would work here, its not a guarantee that (like I have done many times) you'll get the order wrong when writing another, it would be better practice to nest those if statements and define the order you want the boolean checks to break:
if(object != null)
{
if(object.field != null)
{
object.field = "foo";
}
}
This does exactly the same as you're essentially saying, if the first boolean check fails don't do the second; it is also nullPointerException safe as object.field will not be checked unless object is not null
Using short-circuiting on booleans can become annoying later on as when you have a multiple bool if statement it becomes trickier to efficiently debug which part short circuited.

Categories