NullPointerException 以及处理它的最佳方法
注意:这是家庭作业/作业,如果您不想回答,请不要回答。
好吧,经过一些搜索并阅读这些:
Java 中如何检查数组元素是否为 null 以避免出现 NullPointerException 优雅地避免 Java 中的 NullPointerException http://c2.com/cgi/wiki?NullPointerException
我仍然没有取得任何进展如何处理我的代码上的 NullPointerException 错误,有问题的代码片段:
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem != -1 ) {
setElements[numberOfElements] = newValue;
numberOfElements++;
} else { System.out.println("Element " + newValue + "already exist"); }
}
它编译但向集合中添加新元素会引发 NullPointerException 错误。
D:\javaprojects>java SetDemo
Enter string element to be added
A
You entered A
Exception in thread "main" java.lang.NullPointerException
at Set.findElement(Set.java:31)
at Set.add(Set.java:44)
at SetDemo.main(Set.java:145)
我添加了另一项检查,但老实说我不知道这是否正确到第 31 行。 if ( setElements != null && setElements[i].equals(element) ) 但仍然没有喜悦。
非常感谢文档/提示或解释。
学习, 羽扇豆
Note: This is homework/assignment feel not to answer if you don't want to.
Ok after some search and reading these:
How to check if array element is null to avoid NullPointerException in Java
Gracefully avoiding NullPointerException in Java
http://c2.com/cgi/wiki?NullPointerException
Am still not making any progress on how to deal with NullPointerException error on my code, snippet for questionable code:
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem != -1 ) {
setElements[numberOfElements] = newValue;
numberOfElements++;
} else { System.out.println("Element " + newValue + "already exist"); }
}
It compile but adding new element to a set throws a NullPointerException error.
D:\javaprojects>java SetDemo
Enter string element to be added
A
You entered A
Exception in thread "main" java.lang.NullPointerException
at Set.findElement(Set.java:31)
at Set.add(Set.java:44)
at SetDemo.main(Set.java:145)
I added another check, though honestly don't have clue if this right to line 31.
if ( setElements != null && setElements[i].equals(element) ) but still no joy.
A documentation/tips or explanation is greatly appreciated.
learning,
lupin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您是否在任何地方初始化了
setElements
?含义:如果您只是声明一个数组变量:
作为类的数据成员,它会被初始化为
null
。你必须让它指向某件事。您可以内联执行此操作:或在构造函数中执行此操作:
Did you initialize
setElements
anywhere? Meaning:If you simply declare an array variable:
as a data member of your class it is initialized to
null
. You have to make it point to something. You can either do this inline:or in a constructor:
它应该是
setElements[i] != null && setElements[i].equals(element)
。如果集合包含 null 元素,当您对该元素调用 equals 方法时,您将尝试取消引用 null 引用。至于
NullPointerException
- 你不应该永远捕获它。对于不应该为空的东西,必须正确初始化它们。对于那些不能为空的东西 - 在取消引用它们之前必须检查它们是否为空(即调用它们的方法)。捕获
NullPointerException
的唯一用例是当您使用的第三方库没有源代码并且存在导致抛出NullPointerException
的错误时。这些情况很少见,而且由于您才刚刚开始学习 Java,请忘记我提到的这一点并专注于更重要的事情。It should be
setElements[i] != null && setElements[i].equals(element)
. If a collection contains null elements you will try to dereference a null reference when you callequals
method on that element.As for
NullPointerException
- you should never catch it. For things that shouldn't be null, they must be initialized properly. For those things that cannot be null - they must be checked for null before dereferencing them (i.e. calling methods on them).The only use case for catching
NullPointerException
is when you are using a third-party library that you don't have the source for and has a bug that causesNullPointerException
to be thrown. These cases are rare and since you only beginning to learn Java, forget that I mentioned this and concentrate on more important things.findElement
中的 for 循环没有意义。您应该在返回 -1 之前迭代所有值,只有这样您才知道集合中没有与
element
匹配的元素。The for-loop in
findElement
doesn't make sense.You should iterate through all values before returning -1, only then do you know that there is no element in the set that matches
element
.发布整个课程 - 这段代码毫无用处。
您犯了两个严重的错误:不相信编译器,并假设您的代码是正确的。
如果 JVM 告诉您第 31 行有问题,请相信它。
我的猜测是
setElements[i]
为空。Post the entire class - this snippet is useless.
You're making two serious mistakes: failing to believe the compiler, and assuming that your code is correct.
If the JVM tells you that line 31 is the problem, believe it.
My guess is that
setElements[i]
is null.尝试测试元素本身是否为 null,而不是数组:
Try testing the element itself for null, not the array:
您不应尝试捕获空指针异常。相反,避免空指针的最佳方法是:
由于您没有检查 findElement 的参数并添加函数,因此参数很可能是罪魁祸首。添加适当的检查,如果它们为 null,则抛出 IllegalArgumentException。如果执行此操作后出现 IllegalArgumentException,那么您就解决了问题。如果不是,那么您至少知道问题不在于参数,而在于代码的其他地方。
You should not attempt to catch a null pointer exception. Instead, the best way to avoid null pointers is:
Since you do not check the parameters to your findElement and add functions, it is quite possible that the parameters are the culprits. Add the appropriate check and throw IllegalArgumentException if they are null. If, after you do that, you get an IllegalArgumentException, then you've solved your problem. If not, then you at least know that the problem is not the parameter and is elsewhere in the code.
它现在可以工作了,感谢 Lars、Igor 和其他人花时间批评代码,有一个逻辑错误没有检查,无论如何,这是更正的工作代码,最后我很烦恼我是否在作弊? :(
谢谢,
羽扇豆
Its working now, thanks to Lars,Igor and the rest who took time to critic the code, there's a logic error that wasn't check,anyway here's the corrected working code, lastly I'm bother am I doing cheating? :(
with thanks,
lupin