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)
就目前情况而言,对于 1
的 sch
,它将匹配第一个 if
的 sch==1
>,以及第二个 if
的 else
条件。请参阅this official Java tutorial page了解有关 else if
工作原理的更多详细信息。
关于java - 简单的 if 语句无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35971571/