Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException and the best way to deal with it

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

like image 372
lupin Avatar asked Dec 07 '22 03:12

lupin


2 Answers

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];
  }
  ...
}
like image 101
cletus Avatar answered Dec 14 '22 05:12

cletus


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.

like image 36
Lars Andren Avatar answered Dec 14 '22 05:12

Lars Andren