I use an if else condition in eclipse in java but my false is returning me a true conditional statements not false conditional statement. why?
//if yes or no then
Boolean b1 = true;
Boolean b2 = false;
if(b1.equals(!b2)){
System.out.println("equals() method returns true");
}
else if (b2.equals(!b1)) {
System.out.println("equals() method returns false");
}
else {
System.out.println("sorry, enter the correct characters.");
}
I tried assigning string yes and no to b1 and b2 respectively but it did not work. Also i cannot use Boolean type with string in equals but why?
Please try solving it in easy form not the complicated as i am still a beginner. plus i need to use all of three conditions.
CodePudding user response:
A more succicnt program can be written as follows:
System.out.println("equals() method returns " b1.equals(b2));
The result of 'equals' (as well as the comparison operators) is a boolean value, which is usable as an expression, not just in conditional statements.
Of course, if the original program was an exercise in using 'if' and 'else', this answer does not apply.
CodePudding user response:
The problem in the function you describe here, is that your program will never enter the second condition (the else if
one).
Basically, because you are negating again the second boolean variable after the equals with the exclamation mark !b1
and !b2
.
So, if you initialize the variables with the same value which is b1 = true
and b2 = true
; or b1 = false
and b2 = false
, it will go to the last else
statement. ("sorry, enter the correct characters")
If you initialize it being it the opposite for both variables, being b1 = true
and b2 = false
; or b1 = false
and b2 = true
, it will only evaluate the first if
condition. ("equals() method returns true").
I think the best approach for your problem would be:
Boolean b1 = false;
Boolean b2 = true;
if (b1.equals(b2))
{
System.out.println("equals() method returns true");
}
else
{
System.out.println("equals() method returns false");
}
I don't think you need three conditions for this exercise.
CodePudding user response:
In your code the first condition equals with second.
b1.equals(!b2)
= b2.equals(!b1)
Both checks if one not equals to other. So if the first condition returns true, second is also true and vice versa.
Easier to understand if using this conditions: !b1.equals(b2)
, !b2.equals(b1)
(Both checks equality than negotiate)
So your algorithm never goes into else if (b2.equals(!b1)) {
The right way:
if(b1.equals(b2)){
System.out.println("equals() method returns true");
}
else {
System.out.println("equals() method returns false");
}
It's enough.
If you want to know which was true, then you need an additional condition:
if (b1.equals(b2)){
System.out.println("equals() method returns true");
}
else if (b1.equals(true)) { // short: if (b1) {
System.out.println("b1 is true, b2 is not");
else {
System.out.println("b2 is true, b1 is not");
}