J.Kirk. J.Kirk. - 1 month ago 9
Java Question

Java - addMethod conflicting with exception

Ive been sitting for this with 2 hours now and I can't find a solution. I can't add more than one Friend to my ArrayList, because if the phone is null it casts the exception from my GetFriend() method instead of adding it to the list. What is a simple way to work around this?

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

Answer

change

if(res == null){
      throw new NullPointerException("No result found");
}

to simply return null.

As you are checking for null it will be safe.

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