如何在Java中的二进制搜索树中按名称查找节点

时间:2016-04-25 18:24:33

标签: java binary-search-tree

我用二进制搜索树中学生的姓名和/或姓名编写学生记录节点的方法

这是类二进制搜索树

中方法的代码
private Student root;

public Student findNodeName(String firstname,String lastname) {

    return findNodeName(root,firstname,lastname);

}

private Student findNodeName(Student student,String firstname,String 
 lastname){


    if (student == null) {
        return null;
    }


    else if (firstname.equals(student.getFirstName())
            &&lastname.equals(student.getLastName())) {   
        return student;
    }

    else
    {
        if(student.getLeft()!= null)  
        return findNodeName(student.getLeft(),firstname,lastname);

    else 
        return findNodeName(student.getRight(),firstname,lastname);
    }

}

这个代码在主类

//declare object of class universitydbmsBST
 universitydbmsBST universitydbmsbst;

if (command.equals("SEARCHNAME") == true) {

        //variables to read from input file
        String firstname = input.next();
        String lastname = input.next();

        //variable used to check if the student is already in BSt or not 
        Student student =null;


       //print if the student found or not
        if((student = 
             universitydbmsbst.findNodeName(firstname,lastname))!=null){

            output.println("SEARCHNAME Command");
            output.println("Found:  ID "+student.getID()+",  
            "+student.getFirstName()+" "+student.getLastName());

        }


        else {

            output.println("SEARCHNAME Command");
             output.println(student.getFirstName()+" 
             "+student.getLastName()+" was not found in 
              FCITbook.");

        }

    }

但是当我运行它时出现问题似乎是NullPointerException

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您需要实例化下面的变量。与所有对象引用默认情况下一样,它具有null值,并且在调用方法findNodeName时会导致NullPointerException。

universitydbmsBST universitydbmsbst = new universitydbmsBST();

还有几点:

无需与true进行比较。

将第一行转换为第二行:

if (command.equals("SEARCHNAME") == true) { // bad

if ("SEARCHNAME".equals(command)) { // good

这样,在命令变量为null的情况下,也可以防止NullPointerException。

您没有使用Student变量,请勿分配或创建它。
也不要在if语句内分配值。这会使有人对您的代码进行维护感到困惑。

if((student = universitydbmsbst.findNodeName(firstname,lastname))!=null){ // bad, do not do this

// Do this instead, assignment separate from test
Student student = universitydbmsbst.findNodeName(firstname,lastname);
if (student != null) {
 // your code continues here.