我有一个数组,有时可能是null (strings[0])
,我希望能够检测到它的空值,因此我不会收到错误,并且我可以告诉用户。Java-空处理
我尝试了if语句
(if (strings == null){
//do my code
})
,没有工作。我试图做try, catch (NullPointerException)
,但在我的IDE中出现错误。任何帮助将非常感激。
我有一个数组,有时可能是null (strings[0])
,我希望能够检测到它的空值,因此我不会收到错误,并且我可以告诉用户。Java-空处理
我尝试了if语句
(if (strings == null){
//do my code
})
,没有工作。我试图做try, catch (NullPointerException)
,但在我的IDE中出现错误。任何帮助将非常感激。
您应该检查:
这有助于如果数组不null
并不是空的。
我打算这么说! :) – Astrobleme
不是'array.length'而不是'array.size()'? – Astrobleme
谢谢,我试过了,它没有工作,但它似乎应该。此时我开始认为错误来自其他地方。啊代码,总是看起来像它应该工作,即使它没有。 – NatServ
if (strings == null)
返回true,如果字符串是空
你想要的是:
if (strings != null)
感谢您的建议,但字符串== null是我想要的,它只是不工作。 – NatServ
尝试通过您的strings
阵列循环和检查,像这样的空对象:
for (int i = 0; i < strings.length; i++) {
if (strings[i] == null) {
System.out.println("The item at index [" + i + "] is null!");
}
}
都会响起来的是什么人都表示早
if (strings == null)
//code here
这种模式的伟大工程。需要记住的一点是,如果您想要使用短路组合条件,运营商。
这两个逻辑运算符在可以确定布尔值时停止。
所以,如果我们的情况有
if (strings == null && someFunction() == anotherFunction())
的字符串为空
someFunction() == anotherFunction() //<- this would not be evaluated.
因为假& & anyotherBool永远不会为真
看看我的答案。它会向您显示每个空值的索引。 – Adam