gpt4 book ai didi

java - 增强的 for 循环因 NullPointerException 而停止

转载 作者:行者123 更新时间:2023-11-30 08:14:07 35 4
gpt4 key购买 nike

我的增强型 for 循环似乎没有正确迭代。目的是使用搜索类遍历 Contact 类型的 ArrayList 并找到特定名称,但由于某种原因,它仅遍历第一个联系人并在显示之后因错误而停止:

Exception in thread "main" java.lang.NullPointerException
at client.AddressBook.search(AddressBook.java:17)
at Main.main(Main.java:31)

我的主类如下:

import client.AddressBook;
import client.Contact;

public class Main {

public static void main(String[] args) {

AddressBook ab = new AddressBook();

Contact c1 = new Contact("jeffm@engr.uconn.edu");
ab.add(c1);

Contact c2 = new Contact("jeffm@engr.uconn.edu", "Jeff Meunier", "jeff");
ab.add(c2);

Contact c3 = new Contact("billgates@engr.uconn.edu", "Bill Gates", "bill");
ab.add(c3);

System.out.println(ab.search("jeff"));
}

}

AddressBook 和 Contact 类也在下面列出:

package client;
import java.util.ArrayList;

public class AddressBook {

ArrayList<Contact> al = new ArrayList<Contact>();

public void add(Contact contactAdd) {

al.add(contactAdd);
}

public Contact search(String searchName) {

for(Contact obj: al) {

if(obj.getNickName().equals(searchName)) {
return obj;
}
}
return null;
}

public String remove(String nickname) {

search(nickname);
al.remove(nickname);

return nickname;
}

public void show() {

int x = 1;
for(Contact obj: al) {

System.out.println(x + ". " + obj.toString());
x++;
}
}
}



package client;

public class Contact {

public String _emailAddress = null;
public String _fullName = null;
public String _nickName = null;

public Contact(String emailaddress, String fullname, String nickname) {

_emailAddress = emailaddress;
_fullName = fullname;
_nickName = nickname;
}

public Contact(String emailaddress) {

_emailAddress = emailaddress;
}

@Override
public String toString() {

if(_fullName == null & _nickName == null) {

//System.out.println("<" + _emailAddress + ">");
return _emailAddress;
}
else {
//System.out.println(_fullName + " (" + _nickName + ") " + "<" + _emailAddress + ">");
return _fullName + " (" + _nickName + ") " + "<" + _emailAddress + ">";
}
}

public String getNickName() {

return _nickName;
}
}

如有高人指点,将不胜感激。最终,现在我只是在测试搜索类是否可以搜索指定的昵称,然后打印出它的返回值。显然它应该返回第二个联系人(或者至少这是意图)。

最佳答案

问题发生在这个验证中:

 if(obj.getNickName().equals(searchName)) {
return obj;
}

似乎 obj.getNickName() 有时可能为空。

更改验证顺序:

public Contact search(String searchName) {

for(Contact obj: al) {
//I assume that searchName will never be null
if(searchName.equals(obj.getNickName()) {
return obj;
}
}
return null;
}

关于java - 增强的 for 循环因 NullPointerException 而停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29689525/

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