java - Method returning a NullPointerException when it should be returning a -1 -
the following code works fine long name input in directory. if name doesn't exist in directory, returns nullpointerexception. don't understand cos if name doesn't exist in directory, should return -1. why exception? guidance.
public class direct{ //directory class contain name , get/set methods it. private directory[] directory = new directory[100]; public int find(string name){ (int x=0; x < directory.length; x++){ if (directory[x].getname().equals(name)){ //exception refers line hold error return x; } } return -1; } } //testing on main method direct direct = new direct(); //this works cos name john in directory. system.out.println(direct.find("john")); returns error cos x not present in directory. system.out.println(direct.find("x"));
when create directory
array of length 100
, starts out 100 null
references. reached past existing directory
objects filled in (if any), , have reached null
reference before reaching end of array.
test directory[x]
being null
before accessing getname()
. it's whether return -1
on null
array element or continue searching array.
Comments
Post a Comment