NullPointerException 以及处理它的最佳方法

发布于 2024-08-31 20:13:59 字数 1827 浏览 2 评论 0原文

注意:这是家庭作业/作业,如果您不想回答,请不要回答。

好吧,经过一些搜索并阅读这些:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

只有一腔孤勇 2024-09-07 20:13:59

您是否在任何地方初始化了 setElements ?含义:

String[] setElements = new String[100];

如果您只是声明一个数组变量:

String[] setElements;

作为类的数据成员,它会被初始化为 null。你必须让它指向某件事。您可以内联执行此操作:

public class MyClass {
  private String[] setElements = new String[100];
  ...
}

或在构造函数中执行此操作:

public class MyClass {
  private String[] setElements;

  public MyClass() {
    setElements = new String[100];
  }
  ...
}

Did you initialize setElements anywhere? Meaning:

String[] setElements = new String[100];

If you simply declare an array variable:

String[] setElements;

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:

public class MyClass {
  private String[] setElements = new String[100];
  ...
}

or in a constructor:

public class MyClass {
  private String[] setElements;

  public MyClass() {
    setElements = new String[100];
  }
  ...
}
叹梦 2024-09-07 20:13:59

它应该是 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 call equals 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 causes NullPointerException 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.

幸福丶如此 2024-09-07 20:13:59

findElement 中的 for 循环没有意义。

for ( int i = 0; i < setElements.length; i++) {
               if ( setElements[i].equals(element) ) {  // This line 31  here
                  return retval = i;

               }
               else {
                   return retval = -1;
               }
           }

您应该在返回 -1 之前迭代所有值,只有这样您才知道集合中没有与 element 匹配的元素。

The for-loop in findElement doesn't make sense.

for ( int i = 0; i < setElements.length; i++) {
               if ( setElements[i].equals(element) ) {  // This line 31  here
                  return retval = i;

               }
               else {
                   return retval = -1;
               }
           }

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.

鲸落 2024-09-07 20:13:59

发布整个课程 - 这段代码毫无用处。

您犯了两个严重的错误:不相信编译器,并假设您的代码是正确的。

如果 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.

鸢与 2024-09-07 20:13:59

尝试测试元素本身是否为 null,而不是数组:

setElements[i] != null && setElements[i].equals(element)

Try testing the element itself for null, not the array:

setElements[i] != null && setElements[i].equals(element)
月下伊人醉 2024-09-07 20:13:59

您不应尝试捕获空指针异常。相反,避免空指针的最佳方法是:

  • 在任何采用参数且假设参数为非空的函数中,始终检查参数是否为非空,如果为空,则抛出 IllegalArgumentException。
  • 每当您调用不允许空参数的函数时,请确保不要向该函数传递空指针;如果您已经知道该对象是非空的(因为您已经检查过它并且会抛出 IllegalArgumentException),那么您不需要重新检查;否则,您应该在传递该对象之前仔细检查该对象是否为非空。

由于您没有检查 findElement 的参数并添加函数,因此参数很可能是罪魁祸首。添加适当的检查,如果它们为 null,则抛出 IllegalArgumentException。如果执行此操作后出现 IllegalArgumentException,那么您就解决了问题。如果不是,那么您至少知道问题不在于参数,而在于代码的其他地方。

You should not attempt to catch a null pointer exception. Instead, the best way to avoid null pointers is:

  • In any function that takes parameters where you assume that the parameter is non-null, always check that the parameter is non-null and throw an IllegalArgumentException if it is null.
  • Whenever you invoke a function that does not allow null parameters, ensure that you do not pass a null pointer to that function; if you already know that the object is non-null (because you already checked it and would have thrown an IllegalArgumentException), then you do not need to recheck; otherwise, you should double-check that the object is non-null before passing it along.

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.

榆西 2024-09-07 20:13:59

它现在可以工作了,感谢 Lars、Igor 和其他人花时间批评代码,有一个逻辑错误没有检查,无论如何,这是更正的工作代码,最后我很烦恼我是否在作弊? :(

int findElement(String element) {
          int retval = 0;

            for ( int i = 0; i < setElements.length; i++) { //loop first to the array and only return -1 once we can't find it.         
       //setElements[i] != null is the NullPointerException killer :)


               if ( setElements[i] != null && setElements[i].equals(element) ) {
                  return retval = i;

               } 
            retval = -1; 
           }

          return retval;
       }

       void add(String newValue) {
            int elem = findElement(newValue);
            if( numberOfElements < maxNumberOfElements && elem == -1 ) { # == instead of != as I only need to add if elements is non-existing 
               setElements[numberOfElements] = newValue;
               numberOfElements++;
            } 
       }

谢谢,
羽扇豆

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? :(

int findElement(String element) {
          int retval = 0;

            for ( int i = 0; i < setElements.length; i++) { //loop first to the array and only return -1 once we can't find it.         
       //setElements[i] != null is the NullPointerException killer :)


               if ( setElements[i] != null && setElements[i].equals(element) ) {
                  return retval = i;

               } 
            retval = -1; 
           }

          return retval;
       }

       void add(String newValue) {
            int elem = findElement(newValue);
            if( numberOfElements < maxNumberOfElements && elem == -1 ) { # == instead of != as I only need to add if elements is non-existing 
               setElements[numberOfElements] = newValue;
               numberOfElements++;
            } 
       }

with thanks,
lupin

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文