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;
}
沒有。會推薦可以改變整個「建築」的Scary Wombats解決方案。爲了擺脫例外。 –
非常感謝! –
ü歡迎。順便說一句,arraylist有isEmpty()方法來檢查返回布爾值的空白。 http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty-- –