I'm doing a practice question which is:
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.
parrotTrouble(true, 6) → true
parrotTrouble(true, 7) → false
parrotTrouble(false, 6) → false
My code is:
`public boolean parrotTrouble(boolean talking, int hour) {
if ((talking = true) && (hour < 7 || hour > 20)){
return true;
}
else
return false;
}`
The correct answer is:
public boolean parrotTrouble(boolean talking, int hour) {
return (talking && (hour < 7 || hour > 20));
// Need extra parenthesis around the || clause
// since && binds more tightly than ||
// && is like arithmetic *, || is like arithmetic +
}
I am wondering what is the difference between talking = true and just talking.
talking = true assigns true to talking and returns true.
if (talking == true) is the same as if (talking), since both return true.
in Java , sign equal represents assignments, double equal represents comparison.
In your case you are assigning instead of comparing.
When you just use talking, it will have same value which is passed as parameter to parrotTrouble method. So value changes as per input.
Whereas talking = true is an assignment which will always evaluate to true.
In java if statement requires result of if condition = true // if(condition)
to be able to execute code inside curly bracket // {}
=> this true you can assign directly i.e if(true)
or it can generated as result of condition i.e if(val==true)
now in your case
when you put talking = true it assign true to talking and return true
and in other code use talking directly which contains value true so it returns true
Related
I was implementing an N-nary tree (here N=4) and want to put in a logic to do something if the boolean property val of all four children of a node are equal, I tried with:
if (childOne.val == childTwo.val == childThree.val == childFour.val){
doSomthing();
}
however this doesn't work for my test cases, so I have to change it to a more explicit and verbose:
if (childOne.val == childTwo.val && childTwo.val == childThree.val && childThree.val == childFour.val){
doSomthing();
}
and this one works. However I cannot make sense why the first evaluation doesn't give me the correct answer.
The == operator is left associative, so your first expression looks like this with brackets added:
(((childOne.val == childTwo.val) == childThree.val) == childFour.val)
Here's a case where the above will be true, but not all four values are the same:
child 1 and 2 are false
child 3 and 4 are true
Another way of doing this:
Stream.of(childOne.val, childTwo.val, childThree.val, childFour.val)
.distinct().count() == 1
I suggest you stick with the plain old && because there isn't a BooleanStream and the booleans need to be boxed.
Another class is going to pass in random numbers into this method(x,y,z). I want to know the boolean that does returns true from my last if() statement, so I can do operations on it. I have explained my logic in the comments.
I am still really new to this, so my logic may be wrong.
public static String FindDate(int x, int y, int z) {
boolean istrue1 =(x >= 1 && x <= 31);
boolean istrue2 =(y >= 1 && y <= 31);
boolean istrue3 =(z >= 1 && z <= 31);
if(istrue1 ^ istrue2){
if(istrue1^istrue3){
if(istrue2^istrue3){//now knowing that no values are the same, i can find the true value.
if(istrue1||istrue2||istrue3){
// I want to store/use/print/know which bool(istrue) that evaluated to true, so I would know if it is
//x,y,z that went through the algorithm successfully.
}
} else{return "Ambiguous";}
}else{return "Ambiguous";}
}else{return "Ambiguous";}
return "true"; //I would actually end up returning the value that went through the algorithm
}
You can store boolean values just like any other type in Java. I'm not sure exactly what your last comment means by "the value that went through", but if you want to keep track of the result of a particular test, you don't necessarily need to write something like
if (a == b) {
return true;
} else {
return false;
}
In that case,
return a == b;
is equivalent. If the expression is more complicated parens are a good idea.
return ((a == b) || c);
And instead of returning, you could always store the result and do something with it later.
bool test = ((a == b) || c);
action(test);
You can your following: But your condition is incorrect 3 variable for two value (true, false) all can't be different. So your logic always return "Ambiguous"
if(istrue1 ^ istrue2){
if(istrue1^istrue3){
if(istrue2^istrue3){
//now knowing that no values are the same, i can find the true value.
if(istrue1||istrue2||istrue3){
// I want to store/use/print/know the bool that evaluated to true, so I would know if it is
//x,y,z that went through the algorithm successfully.
return "true";
}
}
return "Ambiguous";
Instead of:
if(istrue1||istrue2||istrue3)
Its is easiest to just break it down into 3 differnt if statement.
if(istrue1)
if(istrue2)
if(istrue3)
No easy trick that i was hoping for. sad day.
Also the statements i did with the xor(^) operators turns out to be bad logic.
it would be easiest to this:
if(a&&b || a&&c || b&&c)
That would return ambiguous if any combo are both true.
However thats not the original question, but I thought i might as well mention it.
In my quiz game on the very end of a level I have to check some conditions, 4 of them. During the game I add +1 to an integer variable, 4 variables. On the end of the level I sum these values to another integer, activeButtonsTotal. And I set 4 boolean values to true or false. So, I need to check 2 conditions four times: if it's my boolean is false AND if my activeButtonsTotal is equal to 16 and if it is to set one of my buttons to Enabled, and this same thing for the next boolean and activeButtonsTotal, and 4 times like this. I need to go through all 4 of them. I tried with if statements, and else if but no luck.
boolean columnACorrecct, columnBCorrect, columnCCorrect, columnDCorrect;
activeButtonsTotal = activeButtonsA+activeButtonsB+activeButtonsC+activeButtonsD;
if((columnACorrect=false) && (activeButtonsTotal==16)){
columnA.setEnabled(true);
}
if((columnBCorrect=false) && (activeButtonsTotal==16)){
columnB.setEnabled(true);
}
if((columnCCorrect=false) && (activeButtonsTotal==16)){
columnC.setEnabled(true);
}
if((columnDCorrect=false) && (activeButtonsTotal==16)){
columnD.setEnabled(true);
}
im not sure that i follow all your logic, but your "if" statements all are missing an equal sign. You said you have to compare if your boolean is false, AND the number, but you are assigning "False" inside the condition. you need "==".
I would do:
if(activeButtonsTotal==16)
{
columnA.setEnabled(!columnACorrect);
columnB.setEnabled(!columnBCorrect);
columnC.setEnabled(!columnCCorrect);
columnD.setEnabled(!columnDCorrect);
}
I would do something like that:
columnA.setEnabled(!columnACorrect && activeButtonsTotal==16);
columnB.setEnabled(!columnBCorrect && activeButtonsTotal==16);
columnC.setEnabled(!columnCCorrect && activeButtonsTotal==16);
columnD.setEnabled(!columnDCorrect && activeButtonsTotal==16);
You are assigning your boolean variable to false every time you try to check a condition.
This will result in the condition to be false and will never run the code within the block.
To check for equality, use ==;
columnACorrect==false
columnBCorrect==false
columnCCorrect==false
columnDCorrect==false
But I would recommend using:
!columnACorrect
!columnBCorrect
!columnCCorrect
!columnDCorrect
It does the same thing. The 2nd option is more preferable.
I'm studying for the OCA Java SE7 Associate exam. One of my practice exam questions had the following code snippets:
boolean flag = true;
if (flag = false) {
System.out.println("1");
}
else if (flag) {
System.out.println("2");
}
else if (!flag) {
System.out.println("3");
}
else
System.out.println("4");
Notice the if (flag = false) conditional. The question asked what the output of this snippet would be. All the numbers were provided as answer choices and then there was a choice that said "compiler error," which is what I selected. I was wrong. The output would be 3. I tested in Eclipse and it also came back with 3.
I then tested with
int x = 3;
int y = 1;
if (x = y) {
// whatever
}
and, of course, got an error.
Why can the flag be changed from true to false inside the if-statement, but the value of x can't be changed in the similar scenario? Is it because flag is a boolean type and x is type int? I Googled this, but was unable to find anything.
Because the assignment of x = y doesn't equate to a boolean evaluation.
if is expecting the result of the operation to give either a true or false return.
Something like if ((x = y) == y) would work (the evaluation would return true)
flag = false is an assignment, so it is carried out. After the assignment on the first if, it evaluates to false because it was just set to it. For equality it should have been flag == false, but since it was an assignment, the top if was evaluated to false, and since it was changed to false, when you get to !flag, that passes because flag is no longer true, and it prints 3.
You got an error with if(x = y) because after the assignment, the value couldn't be evaluated as a boolean outcome whereas if(flag = false) can evaluate to boolean after the assignment.
The big thing to remember about high-level languages is that it takes more than one low-level statement to perform the logic of even a simple if, and with the assignment case, there is a minimum of 2 operations going on, first the assignment, then the equality.
if (flag = false) will set the flag variable to false, then check if(flag).
You are suggesting doing if(x = 1) which could set x to 1, but if(x) is not valid.
It would print 3 because the boolean variable is assigned false (and checked for true) then checked for false and finally for !false which is true.
//first
if(num % 2 == 0 ) {
isEven = true;
}
//second
isEven = (num %2 == 0);
What is the best thing to do, and is first case a case of code smell?
They don't do the same thing - if num is odd, the first leaves isEven with its previous value, the second sets it to false.
I would:
Try to initialize the variable at the point of declaration, and not change it afterwards.
Use the second form in preference to the first in general.
When the body of an if block is just setting a variable, and the value can be expressed as some simple modification of the condition of the if block, and you always want to set some value, I would just use the simple assignment.
The same goes for return statements - I would rather have:
return (num % 2 == 0); // Or (num & 1 == 0)
than
if (num % 2 == 0) {
return true;
} else {
return false;
}
Without knowing anything about the surrounding context, these two version actually differ in their semantics.
The first version will only change the value of isEven if num is an even number. The latter version will always update the value of isEven. So I would definitely prefer the latter, as it ensures isEven holds a useful semantic value.