java - 简单的 if 语句无法正常工作

标签 java android if-statement

    int sch = 1;

    if (sch == 1){
        Log.d("check", "1");
    }
    if (sch == 2){
        Log.d("check", "2");
    }
    else {
        Log.d("check", "error!");
    }

这是一个非常简单的陈述。

我在我的 android java 代码中使用完全相同的语句,

它显示check: 1按照预期在 logcat 中。

当我接触到我正在使用的真实代码时,

    int sch = 1;

    if (sch == 1){
        activity.getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.white));
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            activity.getWindow().setNavigationBarColor(getResources().getColor(R.color.white));
            activity.getWindow().setStatusBarColor(getResources().getColor(R.color.red));}

        Log.d("check", "1");
    }

    if (sch == 2){            
        activity.getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.white));
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            activity.getWindow().setNavigationBarColor(getResources().getColor(R.color.white));
            activity.getWindow().setStatusBarColor(getResources().getColor(R.color.green));}

        Log.d("check", "2");
    }
    else {
        activity.getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.white));
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            activity.getWindow().setNavigationBarColor(getResources().getColor(R.color.white));
            activity.getWindow().setStatusBarColor(getResources().getColor(R.color.white));}

        Log.d("check", "error");
    }
}

当我运行此代码时,它应该显示 check: 1在logcat上并在状态栏上显示红色。

但它显示如下:

check: 1
check: error

并在状态栏上显示白色。

这是确切的代码,我没有发现任何错误。

可能是什么问题?

最佳答案

替换:

if (sch == 2)

与:

else if (sch == 2)

就目前情况而言,对于 1sch,它将匹配第一个 ifsch==1 >,以及第二个 ifelse 条件。请参阅this official Java tutorial page了解有关 else if 工作原理的更多详细信息。

关于java - 简单的 if 语句无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35971571/

相关文章:

java - API 23 (Android 6.0.1) 应用内计费 : Service Intent must be explicit: Intent

java - Android JavaMail IMAP 10 秒后超时

javascript - 如何修复仅返回 else 语句的 if 函数

python - 我大约一半的 if 语句无法正常工作

java - HashMap 键将不起作用

java - setDisplayedMnemonicIndex(int idx) 用于包含 HTML 的 JLabel

android - Android 上的库构建错误

android - Eclipse Android 项目已创建且始终缺少 R 元素

android - Gradle 将 android 应用程序 apk 上传到 maven repo (nexus)

java - 运行程序时偶尔突然停止