在这段代码中.
public class Test {
public static void testFun(String str) {
if (str == null | str.length() == 0) {
System.out.println("String is empty");
} else {
System.out.println("String is not empty");
}
}
public static void main(String [] args) {
testFun(null);
}
}
Run Code Online (Sandbox Code Playgroud)
我们将null值传递给函数null.编译很好,但testFun在运行时给出.
假设传递给的实际参数的值NullPointerException是从某个进程生成的.假设该进程错误地返回null值并将其提供给testFun.如果是这种情况,如何验证传递给函数的值是否为null?
一个(奇怪的)解决方案可能是将形式参数分配给函数内的某个变量,然后对其进行测试.但是如果有许多变量传递给函数,那可能会变得乏味且不可行.那么,如何在这种情况下检查空值?
编辑:错误地写了|| 而不是| 在if条件下.现在生成运行时异常
我需要在这个公式[i]中创建一个空检查,我不完全确定如何解决这个问题,因为我不太熟悉null检查和编程方面的新功能.任何和所有的帮助非常感谢!
public static double calculateInventoryTotal(Book[] books)
{
double total = 0;
for (int i = 0; i < books.length; i++)
{
total += books[i].getPrice();
}
return total;
}
Run Code Online (Sandbox Code Playgroud)