为什么在 android 上不满足 IF 条件

Why IF condition is not fulfilled on android

我只是想知道为什么编译器允许在第一个条件下正常继续程序:

public void ButtonOnClickDirectoryList(View v){
    try {
        if (!spnOptionSelectedDepartment.equals(null) && !spnOptionSelectedCities.equals(null)) {
            if (!spnOptionSelectedTypes.equals(null)) { //code....}

spnOptionSelectedDepartment 和 spnOptionSelectedTypes 是字符串,在 class 的开头定义如下:

private String spnOptionSelectedDepartment = null;
private String spnOptionSelectedCities = null;
private String spnOptionSelectedTypes = null;

所以当我按下按钮时,它会调用这个方法,这是我现在拥有的值:

spnOptionSelectedDepartment = "9999"
spnOptionSelectedCities = null
spnOptionSelectedTypes = null

所以当我在这个条件下放置一个断点时,它只是继续验证里面的其余代码,如果... 谁能解释一下为什么会出现这种行为?

让我编辑问题,是的,如果...

,它会在第二次抛出空指针异常
if (!spnOptionSelectedTypes.equals(null)) {

但是为什么它在 spnOptionSelectedCities = null 时允许第一个 IF...?

它不应该继续,它应该抛出一个 NullPointerException 你可以在 catch 块中拦截。

当你尝试时

if (!spnOptionSelectedTypes.equals(null))

它应该抛出这个异常,因为 spnOptionSelectedTypes 是空的,所以它不是 String 并且没有任何 equals() 方法。

编辑:

它允许第一个 if 通过,因为它有 2 个测试

if (A OR B) {

如果 Atrue,则不会测试 B 条件,因为只需要一个条件就可以继续,因为 OR 运算符。

编辑 2:

有:

如果(A 和 B){

如果 A 为真,B 也将被测试并抛出 NullPointerException 如果 spnOptionSelectedCities 为空。

确定答案:

Java

中的空测试
if (x != null && y != null) {
    x.doSomething();
    y.doSomethingElse();
}