【发布时间】:2015-04-26 08:37:33
【问题描述】:
我只想知道为什么编译器允许在第一个条件下正常继续程序:
public void ButtonOnClickDirectoryList(View v){
try {
if (!spnOptionSelectedDepartment.equals(null) && !spnOptionSelectedCities.equals(null)) {
if (!spnOptionSelectedTypes.equals(null)) { //code....}
spnOptionSelectedDepartment 和 spnOptionSelectedTypes 是字符串,在类的开头定义如下:
private String spnOptionSelectedDepartment = null;
private String spnOptionSelectedCities = null;
private String spnOptionSelectedTypes = null;
所以当我按下按钮时,它会调用这个方法,这是我目前拥有的值:
spnOptionSelectedDepartment = "9999"
spnOptionSelectedCities = null
spnOptionSelectedTypes = null
所以当我在这个条件上设置一个断点时,它会继续验证 if... 中的其余代码。 谁能解释我为什么会出现这种行为?
让我编辑这个问题,是的,它会在第二个 if... 时引发 nullpointer 异常。
if (!spnOptionSelectedTypes.equals(null)) {
但是为什么当 spnOptionSelectedCities = null 时它允许第一个 IF...?
【问题讨论】:
-
if (spnOptionSelectedTypes != null) -
如果
spnOptionSelectedDepartment是null,上面发布的代码将抛出NullPointerException。 -
您应该使用 == 将字符串与 null 进行比较。 equals 用于比较两个字符串的值。
-
@yu_sha 你是唯一给出真实答案的人,其余的只是标记“不使用完整”,就像他们认为每个人都必须知道一切......
-
@yu_sha 我读了很多如何比较字符串之间的值,它说知道字符串是否具有已知值的更好方法是使用 String.equal() .....
标签: java android if-statement android-studio