NullPointerException and the best way to deal with it
- by lupin
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