Java - 条件始终为真/假(Android 复选框)

标签 java android if-statement checkbox conditional-statements

我有以下代码来显示某个字符串,根据该字符串在我的 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,则您永远不会检查 whippedCreamchocolate 是否都为 true,因为 else if 的条件code> 仅当前面的所有条件都为 false 时才进行评估。

关于Java - 条件始终为真/假(Android 复选框),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49326976/

相关文章:

java - 如果 JTextField 中有任何输入,KeyListener 不会响应

java - 在 Hibernate 中,我在运行时遇到以下错误

java - 如何使 java.awt.FileDialog 在屏幕上居中

android - `android.packageBuildConfig=false` 已弃用

android - 在 ViewModel 与 LifeCycleOwner( Activity/fragment )中启动协程

c++ - 为什么我们在数东西的时候要加1?

java - pom.xml 中未找到 Maven 插件

android - 为什么 tensorflow 分类器在移动设备上的准确度低于笔记本电脑

java - 使用循环创建变量

C++ 简单 if 语句不检查?