我有以下代码来显示某个字符串,根据该字符串在我的 Android 应用程序中选中复选框:
public String createOrderSummary(){
CheckBox whippedCheckBox = findViewById(R.id.whipped);
boolean whippedCream = whippedCheckBox.isChecked();
CheckBox chocoBox = findViewById(R.id.chocolate);
boolean chocolate = chocoBox.isChecked();
if (whippedCream && chocolate){
return "both selected";
}else if(whippedCream || chocolate){
if (whippedCream){
return "whippedcream";
}else if (chocolate){
return "chocolate";
}
}else{
return "none checked";
}
return "";
}
我在第 14 行
收到一条警告,提示条件巧克力始终为真
,这是为什么?
此外,当我将线路切换为:
if (whippedCream){
return "whipped cream";
}else if(whippedCream && chocolate){
return "both selected";
}else{
return "none selected";
}
我在第 3 行
收到警告,提示条件始终为 false
。
最佳答案
让我们考虑一下您的部分情况:
if (whippedCream || chocolate) { // either whippedCream is true or chocolate is true
if (whippedCream) { // whippedCream is true
return "whippedcream";
} else if (chocolate) { // whippedCream is not true, so chocolate must be true
return "chocolate";
}
}
因此这个条件可以简化:
if (whippedCream || chocolate) { // either whippedCream is true or chocolate is true
if (whippedCream) { // whippedCream is true
return "whippedcream";
} else { // chocolate must be true
return "chocolate";
}
}
当然,通过消除内部条件可以进一步简化完整条件:
if (whippedCream && chocolate) { // both true
return "both selected";
} else if (whippedCream) { // only whippedCream is true
return "whippedcream";
} else if (chocolate) { // only chocolate is true
return "chocolate";
} else {
return "none checked";
}
您的替代条件:
if (whippedCream){
return "whipped cream";
}else if(whippedCream && chocolate){
return "both selected";
}else{
return "none selected";
}
完全是错误的。如果 whippedCream
为 true,则您永远不会检查 whippedCream
和 chocolate
是否都为 true,因为 else if
的条件code> 仅当前面的所有条件都为 false 时才进行评估。
关于Java - 条件始终为真/假(Android 复选框),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49326976/