Question


I have a following question.

I am implementing BST - Binary Search Tree.
Let's say that I have 3 classes: Employee, Node and Tree.
I am trying to get access from Node class to Employee class elements (fields).

Here is some code:

Employee class

public class Employee
{
   public String name;
   public int age;
}


Node class

public class Node
{
   public Employee empl;

   public Node left;
   public Node right; 
}


Tree class

public class Tree
{
   private Node root;

   public Tree()
   {
      root = null;
   }
   public void insert()
   {
      Node newNode = new Node();

      Scanner readName = new Scanner(System.in);
      newNode.empl.name = readName.nextLine();

      Scanner readAge = new Scanner(System.in);
      newNode.empl.age = readAge.nextInt();

      // Add to the tree code
      // ...
   }
}

So, the problem is, when I am adding name it gives me an error

java.lang.NullPointerException 
at Node.<init>(Node.java)
at Tree.insert(Tree.java)
at Tree.menu(Tree.java)
at Main.main(Main.java)

Maybe it's because i did not add constructors? :/

Was it helpful?

Solution

In this case the Employee object will be null.

newNode.empl.name
---------^

empl is Employee object which is not initialised.

Update the Node class as below :

public class Node
{
   public Employee empl = new Employee();  // Before it was not initialised

   public Node left;
   public Node right; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top