使用我的双向链表的搜索方法。我得到了例外,但我似乎无法弄清楚如何在没有得到它们的情况下遍历列表..
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();
}
}
}
答案 0 :(得分:2)
我没有你的行数,所以我在这里盲目猜测,但我猜这个行是你的问题:
if (head.getFirstName().contains(searchEntry) || head.getLastName().contains(searchEntry) || head.getPhoneNum().contains(searchEntry) || head.getEmail().contains(searchEntry))
您的某个条目很可能会为null
,getFirstName
,getLastName
或getPhoneNum
返回getEmail
。
在解除引用之前,你必须检查每个null
(你不能null.someMethod()
)
这样做的一种方法:
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)))