gpt4 book ai didi

java - 双向链表搜索方法

转载 作者:行者123 更新时间:2023-11-30 09:40:06 25 4
gpt4 key购买 nike

正在研究我的双向链表的搜索方法。我收到异常,但我似乎无法弄清楚如何在不获取异常的情况下遍历列表。

    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();
}
}
}

最佳答案

我没有你的行数,所以我在这里盲目猜测,但我会猜测这一行是你的问题:

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

您的某个条目可能为 getFirstNamegetLastNamegetPhoneNum 返回 null code>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)))

关于java - 双向链表搜索方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9559904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com