Note that there are some explanatory texts on larger screens.

plurals
  1. PONullPointerException and the best way to deal with it
    text
    copied!<p>Note: This is homework/assignment feel not to answer if you don't want to.</p> <p>Ok after some search and reading these:</p> <p><a href="https://stackoverflow.com/questions/425439/how-to-check-if-array-element-is-null-to-avoid-nullpointerexception-in-java">How to check if array element is null to avoid NullPointerException in Java</a> <a href="https://stackoverflow.com/questions/963936/gracefully-avoiding-nullpointerexception-in-java">Gracefully avoiding NullPointerException in Java</a> <a href="http://c2.com/cgi/wiki?NullPointerException" rel="nofollow noreferrer">http://c2.com/cgi/wiki?NullPointerException</a></p> <p>Am still not making any progress on how to deal with NullPointerException error on my code, snippet for questionable code:</p> <pre><code>int findElement(String element) { int retval = 0; for ( int i = 0; i &lt; 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 &lt; maxNumberOfElements &amp;&amp; elem != -1 ) { setElements[numberOfElements] = newValue; numberOfElements++; } else { System.out.println("Element " + newValue + "already exist"); } } </code></pre> <p>It compile but adding new element to a set throws a NullPointerException error.</p> <pre><code>D:\javaprojects&gt;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) </code></pre> <p>I added another check, though honestly don't have clue if this right to line 31. if ( setElements != null &amp;&amp; setElements[i].equals(element) ) but still no joy.</p> <p>A documentation/tips or explanation is greatly appreciated.</p> <p>learning, lupin</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload