Java - add method conflicting with exception -
ive been sitting 2 hours , can't find solution. can't add more 1 friend arraylist, because if phone null casts exception getfriend() method instead of adding list. simple way work around this?
/** * ensures can add friend if friend same phone number doesn't exist * @param f 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 phone exists"); system.out.println("-------------------------------------"); return false; } } /** * searches arraylist friend matching phone * * @param phone string * @return friend if matching phone, else returns 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; }
change
if(res == null){ throw new nullpointerexception("no result found"); } to return null.
as checking null safe.
public friend getfriend(string phone) { if(friends.size() != 0){ for(friend f : friends) { if(f.getphone().equals(phone)){ return f; } } } return null; }
Comments
Post a Comment