NullPointerException and the best way to deal with it

Posted by lupin on Stack Overflow See other posts from Stack Overflow or by lupin
Published on 2010-05-12T01:19:13Z Indexed on 2010/05/12 1:24 UTC
Read the original article Hit count: 533

Note: This is homework/assignment feel not to answer if you don't want to.

Ok after some search and reading these:

http://stackoverflow.com/questions/425439/how-to-check-if-array-element-is-null-to-avoid-nullpointerexception-in-java http://stackoverflow.com/questions/963936/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

© Stack Overflow or respective owner

Related posts about java

Related posts about nullpointerexception