2016-11-11 47 views
2

我一直坐在这里2个小时了,我无法找到解决方案。我不能将多个朋友添加到我的ArrayList中,因为如果手机为空,它将从我的getFriend()方法中抛出异常,而不是将其添加到列表中。什么是解决这个问题的简单方法?Java - 添加方法与异常冲突

/** 
* 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;  
} 

回答

2

变化

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;  
} 
0
if(res == null && friends.size() == 0){ 

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

+0

没有。会推荐可以改变整个“建筑”的Scary Wombats解决方案。为了摆脱例外。 –

+0

非常感谢! –

+0

ü欢迎。顺便说一句,arraylist有isEmpty()方法来检查返回布尔值的空白。 http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty-- –