【问题标题】:NullPointerException when adding data - Java添加数据时出现 NullPointerException - Java
【发布时间】:2014-02-24 19:09:23
【问题描述】:


我有以下问题。

我正在实施 BST - 二叉搜索树。
假设我有 3 个类:Employee、Node 和 Tree。
我正在尝试从 Node 类访问 Employee 类元素(字段)。

这是一些代码:

员工类

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


节点类

public class Node
{
   public Employee empl;

   public Node left;
   public Node right; 
}


树类

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
      // ...
   }
}

所以,问题是,当我添加名称时,它给了我一个错误

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

也许是因为我没有添加构造函数? :/

【问题讨论】:

    标签: java tree nullpointerexception binary-search-tree


    【解决方案1】:

    在这种情况下,Employee 对象将为空。

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

    empl 是未初始化的 Employee 对象。

    更新Node 类如下:

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

    【讨论】:

    • 非常感谢,可惜我不能给你+1
    • 呵呵呵呵@user3348027。没关系,亲爱的。
    猜你喜欢
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    相关资源
    最近更新 更多