gpt4 book ai didi

Java - 添加方法与异常冲突

转载 作者:行者123 更新时间:2023-11-30 08:31:39 24 4
gpt4 key购买 nike

我已经坐了 2 个小时了,我找不到解决方案。我不能将多个 friend 添加到我的 ArrayList,因为如果电话为空,它会从我的 getFriend() 方法中抛出异常,而不是将其添加到列表中。解决此问题的简单方法是什么?

/**
* Ensures you can only add a friend if a friend with same phone number doesn't exist
* @param f as Friend
* @return boolean
*/

public boolean addFriend(Friend f){
if(getFriend(f.getPhone()) == null) {
friends.add(f);
return true;
}
else {
System.out.println("-------------------------------------");
System.out.println("Member with that phone already exists");
System.out.println("-------------------------------------");
return false;
}
}


/**
* Searches the arraylist for a friend matching phone
*
* @param phone as String
* @return Friend if matching phone, else returns a null
*/
public Friend getFriend(String phone) {
Friend res = null;
if(friends.size() != 0){
for(Friend f : friends) {
if(f.getPhone().equals(phone)){
res = f;
}
}
if(res == null){
throw new NullPointerException("No result found");
}
}
return res;
}

最佳答案

改变

if(res == null){
throw new NullPointerException("No result found");
}

简单地返回null

当您检查 null 时,它是安全的。

public Friend getFriend(String phone) {
if(friends.size() != 0){
for(Friend f : friends) {
if(f.getPhone().equals(phone)){
return f;
}
}
}
return null;
}

关于Java - 添加方法与异常冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40539639/

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