I created a search method for a linked list. It works correctly when I search for something that does exist in the list. If I search for something not in the list, then I get a null pointer exception.
I don't see how its possible to get this exception.
Here is the method:
// these two search methods return the node containing the substring given
public UNode search(String cityName)
{
return search(cityName,this);//line 90
}//end search()-------------------------------------------------------------
private UNode search(String cityName, UNode current)
{
if(current != null)
{
if (current.getCity().getName().contains(cityName))
{
System.out.println("Node '" + current.getCity().getName()
+ "' has been found and returned.");
return current;
} else
{
return search(cityName,current.next);//line 105
}
}
else
{
System.out.println("No node containing the substring '"
+ cityName + "' can be found, returning null");
return null;
}
}//end search()-------------------------------------------------------------
To my understanding, this is what happens when searching for something that does not exist: The method keeps calling search() recursively with current.next, it gets to the last element and calls search(cityName, null), then since current is null, it says it is not found, and returns null.
Am I missing something here? What am I doing wrong? Should I just throw the null pointer exception?
Here is the method where I call the search method:
public static void uNodeTest(City[] cities)
{
UNode unvisited = new UNode();
unvisited.addCities(cities);
String a = unvisited.getNext().getNext().getNext().getCity().getName();
System.out.println(a);
UNode current = unvisited;
while(current.getNext() != null)
{
System.out.println(current.getCity().getName());
current = current.getNext();
}
UNode phil = unvisited.search("not a city");
}
Stack Trace:
java.lang.NullPointerException
at cityproject.UNode.search(UNode.java:105)
.
.
.
at cityproject.UNode.search(UNode.java:105)//(omitting repeats)
at cityproject.UNode.search(UNode.java:90)
at cityproject.CityProject.uNodeTest(CityProject.java:104)
at cityproject.CityProject.main(CityProject.java:79)