简体   繁体   中英

if - else if Condition checking BUG

Lets say we have two variables that are

int number = 0;
int second_number = 1;

If we dont use brackets in if-else if check like this.

if(number == 1)
    if(second_number == 0)
        Toast.makeText(getApplicationContext(), "Haha!", Toast.LENGTH_SHORT).show();
else if(number == 0)
    if(second_number == 1)
        Toast.makeText(getApplicationContext(), "Hehe!", Tast.LENGTH_SHORT).show();

else if(number == 0) line is never reached so that program not working decently and even there is no warning for this usage! I've been figured this bug after like fighting for 2 hours!

However code works if you use brackets like this.

if(number == 1) {
    if(second_number == 0)
        Toast.makeText(getApplicationContext(), "Haha!", Toast.LENGTH_SHORT).show();
} else if(number == 0) {
    if(second_number == 1)
        Toast.makeText(getApplicationContext(), "Hehe!", Tast.LENGTH_SHORT).show();
}

Is this behaviour intentional or just a bad bug? If this is a bug can you send google to a bug report because i don't know how to.

As per the Documentation, this is called "Dangling Else Problem", It's not a bug its normal java behavior Documentation .

if (number == 1)
    if (second_number == 0)
       Toast.makeText(getApplicationContext(), "Haha!", Toast.LENGTH_SHORT).show();
else if(number == 0) // A "dangling else"

To Overcome this you can use like this,

IfThenStatement:
    if ( Expression ) Statement

IfThenElseStatement:
    if ( Expression ) StatementNoShortIf else Statement

IfThenElseStatementNoShortIf:
    if ( Expression ) StatementNoShortIf else StatementNoShortIf

You have to use brackets if you have more than one expression inside an IF

if(true)
    works;


if(true)
   dont;
   work;

 //work is executed even if the condition doesn't pass, because the IF isn't wrapping it


if(true){
   works;
   too;
}

Edit: The problem is that the if inside the first consumes the else if, if this were python, or any indent based language, it should work

if(second_number == 0)
        Toast.makeText(getApplicationContext(), "Haha!", Toast.LENGTH_SHORT).show();
else if(number == 0)

It doesn't matter how you indent your code. The else belongs to the the if immediately above it. You have to use curly brackets all the time, especially if you have nested if-else statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM