سؤال

Working on a search method for my doubly linked list. I'm getting exceptions but I can't seem to figure out how to traverse the list without getting them..

    public void searchEntryNode() {
    System.out.println("I'll search through each entry to pull up what you're looking for ");
    System.out.println("Type in what you want ");
    String searchEntry = keyboard.next();

    EntryNode n = head;
    while (head != null) {
        if (head.getFirstName().contains(searchEntry) || head.getLastName().contains(searchEntry) || head.getPhoneNum().contains(searchEntry) || head.getEmail().contains(searchEntry)) { 
            System.out.println("Found a matching entry");
            System.out.println(n.getFirstName() + " " + n.getLastName() + " " + n.getEmail() + " " + n.getPhoneNum());
        }

        if (head.getNext() != null) {
            head = head.getNext();
        }   
        else {
                System.out.println("That's all we found ");
                System.out.println();
                menu();
        }
    }
}
هل كانت مفيدة؟

المحلول

I don't have your line counts, so I'm guessing blindly here, but I'm going to guess that this line is your problem:

if (head.getFirstName().contains(searchEntry) || head.getLastName().contains(searchEntry) || head.getPhoneNum().contains(searchEntry) || head.getEmail().contains(searchEntry))

It's probable that one of your entries returns null for either getFirstName, getLastName, getPhoneNum, or getEmail.

You will have to check each is not null before dereferencing (you can't do null.someMethod())

One way of doing this:

string firstName = head.getFirstName();
string lastName = head.getLastName();
string phoneNum = head.getPhoneNum();
string email = head.getEmail();

if ((firstName != null && firstName.contains(searchEntry)) 
     || (lastName != null && lastName.contains(searchEntry)) 
     || (phoneNum != null && phoneNum.contains(searchEntry)) 
     || (email != null && email.contains(searchEntry)))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top