Java - 添加与异常冲突的方法

标签 java exception

我已经坐了两个小时了,但找不到解决方案。我无法向 ArrayList 添加多个好友,因为如果手机为 null,它会从我的 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/

相关文章:

java - 项目同步时发生 Gradle 错误 : Cause: invalid type code: 32

java.util.NoSuchElementException : No line found at java. util.Scanner.nextLine(Scanner.java:1585)

java - 替换日志消息中的参数并在 Log4j 2 中添加 Throwable

ruby - 如何从 Ruby 中的救援子句中恢复?

python - 构造方法异常

java - .Net 与 Java 中的静态泛型方法

java - 将属性转换为输入流?

java - 为什么我的大整数前面有一个减号?

java - 将 GAE 可扩展性移植到开源框架的最简单方法

c++ - 错误 : cannot dynamic_cast . ..(目标不是指针或引用)