Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-添加与异常冲突的方法_Java_Exception - Fatal编程技术网

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

Java-添加与异常冲突的方法,java,exception,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 */ publi

我已经坐了两个小时了,找不到解决办法。我不能将多个朋友添加到我的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;       
}
改变

只需返回
null

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

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

怎么样?这是一个有效的解决方案吗?

不是。将推荐改变整个“架构”的可怕袋熊解决方案。为了摆脱这个例外。欢迎。顺便说一句,arraylist使用isEmpty()方法检查返回布尔值的空值。
public Friend getFriend(String phone) {
if(friends.size() != 0){
    for(Friend f : friends) {
        if(f.getPhone().equals(phone)){
            return f;
        }
    }
}
return null;       
}
if(res == null && friends.size() == 0){