Simple logic not working or am I missing something? - java

I don't understand why the following class prints out:
true
false
I thought the output should be:
false
false
because this line prints false:
System.out.println((11 >= 1 || 11 <= 10) & (true == false));
so this line should also print false:
System.out.println(in1To10(11, false));
What am I missing here? Here's the class.
public class TestClass {
public static void main(String[] args) {
System.out.println(in1To10(11, false));
System.out.println((11 >= 1 || 11 <= 10) & (true == false));
}
public static boolean in1To10(int n, boolean outsideMode) {
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
return false;
}
}

You want to test if value is in the range 1 to 10 ?
If thats the case, change (n >= 1 || n <= 10) to (n >= 1 && n <= 10)

( true )
( true ) & ( true )
(true || false ) & ( true ) <--- false == false is true!
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
Look, is n >= 1? Yes, so it's true. true v p <-> true, so Java doesn't even check further. true /\ true <-> true so we enter if. return true;
Your code is in plain English:
if ((n is greater or equal to 1 OR smaller or equal 10) AND is the mode set to false)
return true
If you want it to return true if the number is between 1 and 10 incl, it would be:
if ((n is greater or equal to 1 AND smaller or equal 10) AND is the mode set to false)
return true
which in Java is:
if ((n >= 1 && n <= 10) && (outsideMode == false)) {
return true;
}
Also remember to use && and || as they are logical operators instead of | and & bitwise logical operators when dealing with boolean values.

so this line should also print false: System.out.println(in1To10(11, false));
No, this line should not print false. Although the first parameter, 11, indeed turns the expression n >= 1 || n <= 10 from your method into 11 >= 1 || 11 <= 10, which matches your other expression, the second parameter, false, turns outsideMode == false into false == false, while your other expression has true == false.
That is why the two outputs are different: the output from in1To10 is true because the comparison false == false produces true, while the output from main is false, because true == false produces false.
Note: your expression does not match its stated goal of checking if n is between 1 and 10, inclusive. You need to replace || with && to accomplish that.

I think you missed that in function in1to10, you are comparing (false == false) and in main you are comparing (true == false). And so is the result. Hope this helps.

Let's decompose the test in in1to10 :
Parameters : outsideMode = false; n = 11;
(n >= 1 || n <= 10) :=> (11 >= 1 || 11 <= 10) :=> (true || false) :=> so TRUE
outsideMode == false :=> false == false :=> so TRUE
In the end :
public static boolean in1To10(int n, boolean outsideMode) {
if ((TRUE) & (TRUE)) {
return true;
}
return false;
}
:=> return TRUE !

This will return true. How?
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
You are passing 11 and false to the function.
When it goes to inside the first condition it will check that n >= 1 mean 11 >= 1 that is true, so it will not check n<=10. Again it will check the second condition and your outsideMode is false,
That will be like this, (true) & (true)
hence the whole condition will be true and the funciton will return true.
Again the second condition,
(11 >= 1 || 11 <= 10) & (true == false)
It will return false. How?
As 11 >= 1 is true and again it will not check 11 <= 10, and right side is false.
So the condition will be become like this,
true & false that will be false.

Related

What is difference between using logical operators using parentheses?

I am getting different results: -1 if I use parentheses and 1 if I don't use parentheses.
For test case "30/10/2019" I am getting -1 if I use parentheses and 1 if I don't use parentheses in the following line:
else if((mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12) && mm<13 && mm>0 && dd>0 && dd<32) return 1;
What is the difference between above line and below line?
else if(mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12 && mm<13 && mm>0 && dd>0 && dd<32) return 1;
public class Utility {
public static int checkDate(String date){
String []st;
if((date.charAt(2)=='.' && date.charAt(5)=='.')||(date.charAt(2)=='/' && date.charAt(5)=='/')||(date.charAt(2)=='-' && date.charAt(5)=='-'))
{
String token = Character.toString(date.charAt(2));
if(date.charAt(2) == '.') st = date.split("\\.");
else st = date.split(token);
int dd = Integer.parseInt(st[0]);
int mm = Integer.parseInt(st[1]);
int yy = Integer.parseInt(st[2]);
if(mm == 2 && dd>0 && dd<30 && mm<13 && mm>0) return 1;
else if((mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12) && mm<13 && mm>0 && dd>0 && dd<32) return 1;
else if((mm==4||mm==6||mm==9||mm==11) && dd>0 && dd<31 && mm<13 && mm>0) return 1;
else return -1;
}
else return -1;
}
}
import java.util.Scanner;
public class DateValidation {
public static void main(String[] args) {
// STUDENT CODE BEGINS HERE
Scanner sc = new Scanner(System.in);
String dt=sc.next();
Utility ut = new Utility();
int flag = ut.checkDate(dt);
if(flag==1)
System.out.println("Valid");
else
System.out.println("Invalid");
// STUDENT CODE ENDs HERE
}
}
It will execute the following (in highest order of precedence):
Parentheses ()
Not !
And &&
Or ||
else if((mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12) && mm<13 && mm>0 && dd>0 && dd<32)
return 1;
It will evaluate (mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12) first, then && mm<13 && mm>0 && dd>0 && dd<32
else if(mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12 && mm<13 && mm>0 && dd>0 && dd<32)
return 1;
As for the other, it will evaluate mm<13 && mm>0 && dd>0 && dd<32 first, then mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12 &&
Parentheses decide the order these booleans are resolved. And binds stronger than Or. In your case you ask for:
mm==12 && mm<13
So left comparison and right comparison must resolve to true. They don't, as you are in month 10. With parenthesis you decide to check if your month value is valid at all, this resolves to true, and then the && check resolves to true as well.
Consider this example.
int a = 5;
System.out.println((a == 5 || a == 10) && a == 8 || a == 9); // false
// evaluates to true && false || false which is false
System.out.println(a == 5 || a == 10 && a == 8 || a == 9); // true
// evaluate to true || false && false && false
// the first true, wins because it is followed by an || so the whole
// expression evaluates to true.
With a && b both both a and b must be true for the statement to be true
With a || b only one of a and b must be true.
This also goes for grouped expressions.
If one expression is true and the other is false, the complete expression is false for && and true for ||. These operators work from left to right so you need to group appropriately, just like arithmetic expressions.
The best advice is always use parentheses to ensure proper evaluation of expressions.

Convert this java method without using if/loops

Convert the following without if/loops. You can still use recursion, &&, || etc...
public boolean mystery(int n){
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
I would like hints.
But I've been experimenting around.
We know that true && false == false and only true && true == true
So we must have that
return (n%10 == 7) && ....
Then for the second part, we could either get true or false, and if the second part is true, then our first part being true will result in everything being true, so I am thinking.
return (n%10 == 7) && ...
But I am thinking an issue might be that if n%10 isnt 7 right off that bat everything is false.
In my view, the ternary operator is still pretty much an 'if' statement - but that becomes a semantic debate. You can avoid using it entirely.
return (n % 10 == 7) || (n != 0 && mystery(n/10));
There are many ways: but to give you a start:
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
is equivalent to
return n==0 ? false : n%10==7 ? true : mystery(n/10);
is equivalent to
return n!=0 ? n%10==7 ? true : mystery(n/10): false;
is equivalent to
return n!=0 && n%10!=7 ? mystery(n/10) : n!=0;
Was an interesting activity to solve. Solution below with proof of testing till 10k. mystery2 is the method of interest for you.
How I got the solution:
Started printing the results from 0 to 100 and identify the pattern - found the ones starting or ending with 7 would return true and all others false. The first if block which compares with zero is actually encountered by all the numbers which do not qualify reminder 7 rule in any position. Thus, reminder 7 is the only condition to get true result and everything else would enter recursion until it becomes 0 after the unit's position is complete. Equating to 0 is required as we should have a condition that ends the recursion (or ends in StackOverflowException).
public static void main(String[] args) {
for(int i = 0 ; i<=10000; i++){
if(mystery(i) != mystery2(i)){
System.out.println("Mismatch... "+i);
}
}
}
static boolean mystery(int n) {
if (n == 0) {
return false;
}
if (n % 10 == 7) {
return true;
}
return mystery(n / 10);
}
static boolean mystery2(int n) {
return n % 10 == 7 || (n != 0 && mystery2(n / 10));
}

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

How to read this NOT operator?

I don't understand what the bolded part actually represents. Please correct me if I'm wrong.
30 does NOT equal to 30 is false OR NOT(17 equals to 17 (true) AND 20 is greater then 21(false)) // i don't get this one, do I just flip everything meaning like -1 before() so the statement would be:
17!=17(false) && 20<21(true). I'm lost here. Thanks for any advice.
boolean m;
m = ((30!=30) || !(17==17 && 20>21))
SOP(m);
true || false ?
The ! operator works on a single boolean type and returns the opposite of it's value.
Let's break this all down:
(30!=30 || !(17==17 && 20>21))
(false || !(true && false))
(false || !( false ))
(false || true ))
( true )
Let's consider the comparison to the left of the OR... that is 30 != 30. This is false. So
m = (false || !(17==17 && 20>21))
Next 17 is equal to 17,
m = (false || !(true && 20>21))
Next 20 is not > then 21, so false....
m = (false || !(true && false))
Next true and false is false... so
m = (false || !(false))
And that allows us to reach
m = (false || true)
So
m = true
m will equal true because...
30!=30 = false
17==17 = true
20>21 = false
so...
( false || ! ( true && false ) )
so...
( false || ! false )
so...
( false || true )
so..
true
I always find it helps to expand your calculations so to speak.
This condition will be true
boolean m = (A || B)
Here A is (30!=30)
and B is `!(17==17 && 20>21)`
Obviously, A wiil be false;
!(17==17 && 20>21) equals to !(true && false), equals to !false, equals to true.
Then m = (A||B) equals to (false || true) equals to true
Lets go through this step by step.
Initial problem:
m = ((30!=30) || !(17==17 && 20>21))
We know 30 equals 30 so the 30 != 30 is false:
m = ((false) || !(17==17 && 20>21))
Because it is an or statement, we can remove the false part:
m = !(17==17 && 20>21)
We know 17 is equal to 17 (or the world would be ending) and 20 is less than 21 so:
m = !(true and false)
True and false evaluates to false so we have:
m = !false
This makes m become true.

Explain if (++value % 2 == 0 && ++count < limit) in java

public class AndOperator {
public static void main(String[] arg) {
int value = 8;
int count = 10;
int limit = 11;
if (++value % 2 == 0 && ++count < limit) {
System.out.println("here");
System.out.println(value);
System.out.println(count);
} else{
System.out.println("there");
System.out.println(value);
System.out.println(count);
}
}
}
i am getting output as
there
9
10
explain how count is 10....?
&& is short-circuit operator. It will only evaluate the 2nd expression if the 1st expression evaluates to true.
Since ++value % 2 == 0 is false, hence it doesn't evaluate the 2nd expression, and thus doesn't increment count.
++value = 9 so ++value % 2 == 0 is false so ++count < limit is not evaluated.
This is called Short circuit evaluation. See the wikipedia page : http://en.wikipedia.org/wiki/Short-circuit_evaluation
Since you are using &&(logical and) operator.
logical and evaluate second condition only if first condition is evaluated to true
Here in your code first condition ++value % 2 == 0 is evaluated to false,so second condition ++count < limit won't be evaluated.
If you want to execute ++count < limit also use &.
more information read Difference between & and &&
Because ++value % 2 == 0 is false, thus it won't return the first statement. The reason ++value % 2 is false is because value is incremented by one before the mod operator is evaluated. So ++value % 2 is 9 % 2 which != 0.

Categories

Resources