0


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? :/

1 Answer 1

1

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; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much, unfortunately I can't give you +1
hehehehe @user3348027.Its okk dear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.