Question

i have a block of code, which checks the checked status of checkbox & displays value accordingly, but in my code i have a place where I have to use statement like

if (cb1.isChecked()) {
a="abc";        
} 

else if(cb1.isChecked() && cb2.isChecked()) {
a="pqr";
}

else if(cb2.isChecked()){
a="asd";
}

else{
a="xyz";
}

I get the values if checkbox1 or checkbox2 are selected, but when both the checkboxes are selected i get result as"abc" only

any idea whats wrong with the code??

Was it helpful?

Solution

This is because its an else if instead of ifs. Once the first one is satisfied it isn't checking the others. Change the order in which you check these. So something like

if (cb1.isChecked() && cb2.isChecked()) {
    a="abc";        
} 
else if(cb1.isChecked()) {
    a="pqr";
}   
else if(cb2.isChecked()){
    a="asd";
}   
else{
    a="xyz";
}

OTHER TIPS

Change to:

if(cb1.isChecked() && cb2.isChecked()) {
a="pqr";
}

else if (cb1.isChecked()) {
a="abc";        
} 

else if(cb2.isChecked()){
a="asd";
}

else{
a="xyz";
}

In your code if cd1 was checked, it would not go into the else anymore.

In an if else ladder, only one block will be executed, you should do this like the following :

if (cb1.isChecked()) {
    a = cb2.isChecked() ? "pqr" : "abc";       
} else if(cb2.isChecked()){
    a="asd";
}
else{
    a="xyz";
}

OR

if(cb1.isChecked() && cb2.isChecked()) {
    a="pqr";
}
else if (cb1.isChecked()) {
    a="abc";        
} 
else if(cb2.isChecked()){
    a="asd";
}
else{
    a="xyz";
}

With else if he doesn't is he enters the first if he doesn't enter the rest of them just take the else and user ifs only and it works

Modify first if condition to

if(cb1.isChecked() && !cb2.isChecked())

At present, since the first if conditions only depends on value of cb1, so control goes into first block.

Control NEVER goes into the second block in the present logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top