【发布时间】:2018-08-25 21:19:45
【问题描述】:
我有以下代码来根据我的 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 "";
}
我在line 14 收到警告说condition chocolate is always true,这是为什么呢?
当我换行时:
if (whippedCream){
return "whipped cream";
}else if(whippedCream && chocolate){
return "both selected";
}else{
return "none selected";
}
我在line 3 收到警告说condition always false。
【问题讨论】:
-
第 14 行是什么,第 3 行是什么?在第二个示例中,我假设第 3 行是从顶部算起的第三行?
-
在第一个示例中,您的嵌套语句是不必要的,应该写成一个明确的 if、else if、else if、else 字符串。在第二个示例中,您需要首先检查最受约束的条件(&& 条件),然后是其他条件。这类似于常见的 Fizz Buzz 面试问题。
标签: java android if-statement checkbox conditional-statements