java - indexOf null exception -


public int indexof(x item) {     node <x> current = head;     int c = 0;     if (current.getvalue().equals(item))     {         return c;     }     while (current != null)     {         current = current.getlink();         c++;         if (current.getvalue().equals(item))         {             return c;         }     }     return -1; } 

.

@test public void testindexof() {     llist<string> b = new llist<string>();      (int = 0; < 20; i++)         b.add("str" + i);      assertequals(19, b.indexof("str0"));     assertequals(0, b.indexof("str19"));     assertequals(-1, b.indexof("not found")); } 

for reason last assertion bringing error nullpointer exception. made when reach null return -1, trying return in third assertion in test, missing here?

the problem this:

while (current != null) {     current = current.getlink(); 

you ensure current not null . . . change current in way makes possible null again. , you'll reach case whenever item not present in linked-list.

you can fix rearranging code bit:

public int indexof(x item) {     node <x> current = head;     int c = 0;     while (current != null)     {         if (current.getvalue().equals(item))         {             return c;         }         current = current.getlink();         c++;     }     return -1; } 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -