2016-11-11 48 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-- –