pls give reason why this java program always comes to the else part
public class Test {
public static void main(String[] args){
if (5.0 > 5) // (5.0<5) for both case it is going to else
System.out.println("5.0 is greater than 5");
else
System.out.println("else part always comes here");
开发者_如何学C /*another sample*/
if (5.0 == 5)
System.out.println("equals");
else
System.out.println("not equal");
}
}
can any one explain the first "if statement" why it always come to else part
second else part prints "equals "
You're testing whether or not (5.0 < 5) or (5.0 > 5). Since (5.0 == 5) then that means it's not less then 5 (false) and not greater then 5 (false). So both (5.0 < 5) and (5.0 > 5) will return false and you will always hit the else statement.
If you did the following (which is what you did in the second half):
if (5.0 == 5)
System.out.println("5.0 is equal to 5");
else
System.out.println("else part always comes here");
Then you will no longer hit the else statement (as you saw in the second half of your question).
The opposite of "less than" is not "greater than". It is "greater than or equal to", which is true in this case.
Because 5.0 is not less than 5. It is equal to 5. So the 5.0 < 5
is false.
It always goes to the else part because 5.0 is not less than 5. It is the same value.
5.0 is not greater than 5; they're equal. Therefore it will resort to the else because the if statement does not return true.
精彩评论