kar
kar

Reputation: 3651

Method returning a NullPointerException when it should be returning a -1

The following code works perfectly fine as long as the name I input is in the directory. If the name doesn't exist in the directory, it returns a NullPointerException. I don't understand cos if the name doesn't exist in the directory, it should just return the -1. Why the exception? Thanks for any guidance.

public  class  Direct{
    //Directory is a class that contain a name and get/set methods for it.
    private Directory[] directory = new Directory[100];

        public int find(String name){
            for (int x=0; x < directory.length; x++){
                if (directory[x].getName().equals(name)){ //exception refers to this line to hold the error
                    return x;
                }
            }
            return -1;
        }
}



//Testing on main method

Direct direct = new Direct();

//This works cos the name John is in the directory.
System.out.println(direct.find("John"));

This returns an error cos x is not present in the directory.
System.out.println(direct.find("x"));

Upvotes: 0

Views: 68

Answers (2)

Hossein
Hossein

Reputation: 41851

directory[x].getName() is null. First check if it is null or not and then do the .getName()

Upvotes: 0

rgettman
rgettman

Reputation: 178263

When you create a Directory array of length 100, it starts out with 100 null references. You reached past all existing Directory objects that are filled in (if any), and you have reached a null reference before reaching the end of the array.

Test for directory[x] being null before accessing getName(). It's up to you whether to immediately return -1 on a null array element or to continue searching the array.

Upvotes: 3

Related Questions