0

I keep getting a null pointer exception. any help on why this is would be great. I believe that the problem resides in my find(String name, Node root) method. Any help with how to fix this would be great. Thank you

public class FamilyTree{

    private Node root;

    private class Node
    {
        private String name;
        private Node father;
        private Node mother;
        private Node(String name, Node father, Node mother)
        {
            this.name = name;
            this.father = father;
            this.mother = mother;
        }
    }

    public FamilyTree(String ego)
    {
        this.root = new Node(ego, null, null);
    }

    private Node find(String name)
    {
        return find(name, root);
    }

    private Node find(String name, Node root)
    {
        if( name != null) {
            if (root.name.equals(name)) {
                return root;
            } else {
                find(name, root.father);
                find(name, root.mother);
            }
        }
        return null;
    }

    public void addParents(String ego, String father, String mother)
    {
        if (find(ego) == null)
        {
            throw new IllegalArgumentException();
        }
        else
        {
            find(ego).father = new Node(father,null, null);
            find(ego).mother = new Node(mother, null, null);
        }
    }

    public boolean isDescendant(String ego, String ancestor)
    {
        if(find(ego) == null ||find(ancestor) == null )
        {
            return false;
        }
        else
        {
            return isDescendant(find(ego), find(ancestor));
        }
    }

    public boolean isDescendant(Node root, Node ancestor)
    {
        if( ancestor != null)
        {
            if (root.equals(ancestor))
            {
                return true;
            }
        }

        return false;
    }

}
Doom3030
  • 25
  • 1
  • 6
  • What's is your specific question? Your question may get closed as "Not a real question" unless you are more specific. We are not here to help you write your code for you. – GreenGiant Apr 20 '16 at 18:33
  • What line is your null pointer exception coming from? Could you post your stack trace of the error? – GreenGiant Apr 20 '16 at 18:34
  • There's a question buried deeply in there. It's been answered many times. However, `private Node find(String, Node) return null;` – Christopher Schneider Apr 20 '16 at 18:35

1 Answers1

0

When you recursively pass father/mother to method find you do not check that these references might be null. Also you ignore return value of recursive call:

private Node find(String name, Node root) {
    if (name == null || root == null) {
        return null;
    }
    if (root.name.equals(name)) {
        return root;
    }
    String parentName = find(name, root.father);
    if (parentName != null) {
        return parentName;
    }
    return find(name, root.mother);
}
hoaz
  • 9,883
  • 4
  • 42
  • 53