简体   繁体   English

和运算符在else id块中使用时不起作用

[英]and operator not working when used in else id block

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 如果选择了checkbox1或checkbox2,则会得到值,但是当同时选中两个复选框时,我得到的结果仅为“ abc”

any idea whats wrong with the code?? 任何想法代码有什么问题吗?

This is because its an else if instead of if s. 这是因为它是一个else if而不是if s。 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";
}

Modify first if condition to 首先将条件修改为

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

At present, since the first if conditions only depends on value of cb1, so control goes into first block. 目前,由于第一个if条件仅取决于cb1的值,因此控制进入第一个块。

Control NEVER goes into the second block in the present logic. 控制永远不会进入当前逻辑的第二个块。

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. 在您的代码中,如果cd1被选中,它将不再进入其他。

In an if else ladder, only one block will be executed, you should do this like the following : 在if else梯形图中,将仅执行一个块,您应该像下面这样执行:

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";
}

如果他不是,则使用else进入,如果他不输入其余部分,则进入第一个,仅使用else和user,这样就可以了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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