-1

I write method to find node of student records by the first and last name of student in Binary Search Tree

This is the code of the method in class 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);
    }

}

And This code in main class

//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.");

        }

    }

But I have a problem when I do run it appears NullPointerException

Can anyone help me?

salk13
  • 27
  • 6

1 Answers1

1

You need to instantiate the variable below. It has null value as all object references do by default and it causes a NullPointerException when you call the method findNodeName.

universitydbmsBST universitydbmsbst = new universitydbmsBST();

A few more points:

No need to compare against true.

Convert the first line into the second:

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

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

That way you are also protected against a NullPointerException in the case that the command variable is null.

You're not using the student variable, do do not assign or create it.
Also do not assign values inside of an if statement. That will confuse somebody doing maintenance on your code.

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.
fpezzini
  • 774
  • 1
  • 8
  • 17