-5

Inside my displayStudent() method in my BinaryTree.java file, I'm trying to write my Binary Tree with students on them into a file. The code I have is throwing me an error. I've tried many different ways to write this file in with no success hence why I'm here.

Here's my Node.java file:

class Node  {
Student data;
Faculty data2;
Node left;
Node right;

public Node(Student data) {
    this.data = data;
    this.left = null;
    right = null;
}

public Node(Faculty data2) {
    this.data2 = data2;
    this.left = null;
    this.right = null;
   }
}

Here's my BinaryTree.java file:

    import java.io.*;

public class BinaryTree {
    public Node root; // Declaring Node that's a root.

    public void insertFaculty(Faculty faculty) { 
        root = insertFaculty(faculty,root); // Let root equal faculty being inserted.
    }

    private Node insertFaculty(Faculty faculty, Node t) {
        if(root == null) { // If the root is empty.
            return new Node(faculty); // Return a faculty node.
        } 

        // If inserted faculty last name is less than the current faculty last name
        if(faculty.getLastName().compareTo(t.data2.getLastName()) < 0) { 
            if(t.left == null) { // If the left node is empty.
                t.left = new Node(faculty); // Create a left a node that accepts a faculty name.
            } else {
                t.left = insertFaculty(faculty,t.left); // Insert faculty members to the left recursively.
            }
            return t; // Return node.
        } 

        // If inserted faculty last name is less than the current faculty last name.
        else if(faculty.getLastName().compareTo(t.data2.getLastName()) > 0) { 
            if(t.right == null) { // If the right node is empty.
                t.right = new Node(faculty); // Create a right a node that accepts a faculty name.
            } else {
                t.right = insertFaculty(faculty,t.right); // Insert faculty members to the right recursively.
            }
        }
        return t; // Return node.
    }

    public void insertStudent(Student s) { 
        root = insertStudent(s,root); // Let root equal student being inserted.
    }

    private Node insertStudent(Student s, Node t) {
        if(root == null) { // If the root is empty.
            return new Node(s); // Return a Student node.
        } 

        // If inserted student last name is less than the current student last name.
        if(s.getLastName().compareTo(t.data.getLastName()) < 0) {
            if(t.left == null) { // If the left node is empty.
                t.left = new Node(s); // Create a left a node that accepts a student name.
            } else {
                t.left = insertStudent(s,t.left); // Insert student members to the left recursively.
            }
            return t; // Return node;
        } 

        // If inserted student last name is greater than the current student last name.
        else if(s.getLastName().compareTo(t.data.getLastName()) > 0) {
            if(t.right == null) { // If the right node is empty.
                t.right = new Node(s); // Create a right a node that accepts a student name.
            } else {
                t.right = insertStudent(s,t.right); // Insert student members to the right recursively.
            }
        }
        return t; // Return name.
    }

    public Node studentDelete(Student s, Node t) {
        if(t != null) { // If t is empty.

            // If inserted student last name is less than the current student last name.
            if(s.getLastName().compareTo(t.data.getLastName()) < 0) { 
                t.left = studentDelete(s,t.left); // Left node will delete appropriate name recursively.
                // If inserted student last name is greater than the current student last name.
            } else if(s.getLastName().compareTo(t.data.getLastName()) > 0) {
                t.right = studentDelete(s,t.right); // Right node will delete appropriate name recursively.
            } else {
                if(t.left == null) { // If left node is empty.
                    return t.right; // Return right node.
                } else if(t.right == null) { // If right node is empty.
                    return t.left; // Return left node.
                }
            }
        }
        return t; // Return node.
    }

    public Node facultyDelete(Faculty faculty, Node t) {
        if(t != null) { // If t is empty.           
            // If inserted faculty last name is less than the current faculty last name.
            if(faculty.getLastName().compareTo(t.data2.getLastName()) < 0) { 
                t.left = facultyDelete(faculty,t.left); // Left node will delete appropriate name recursively.
                // If inserted faculty last name is greater than the current faculty last name.
            } else if(faculty.getLastName().compareTo(t.data2.getLastName()) > 0) {
                t.right = facultyDelete(faculty,t.right); // Right node will delete appropriate name recursively.
            } else {
                if(t.left == null) { // If left node is empty.
                    return t.right; // Return right node.
                } else if(t.right == null) { // If right node is empty.
                    return t.left; // Return left node.
                }
            }
        }
        return t; // Return node.
    }

    public void displayStudent(Node root) throws IOException { 
        if(root != null) { // If root isn't empty.
            displayStudent(root.left); // Recursively display left nodes.
            System.out.println(root.data.toString()); // Print to the console data that's in the root in order.
            displayStudent(root.right); // Recursively display right nodes.
        }   

        String file = "Student.txt"; // Student text file, this will be used to write in student information.
        FileWriter fw = null; // The file writer used to write in student information initially set to null.

        try {
            fw = new FileWriter(file, true); // Place file in FileWriter, true allows file to appended writer.
            for(int i = 0; i < 30; i++) { 
                fw.write(root.data.toString());
            }
            fw.close(); // Close file.
        } catch(FileNotFoundException e) {  // Exception will be thrown if the file isn't found.
            System.out.println("File not found!"); // Message will print if the file isn't found.
        }


    }

    public void displayFaculty(Node root) {
        if(root != null) { // If root isn't empty.
            displayFaculty(root.left);  // Recursively display left nodes.
            System.out.println(root.data2.toString()); // Print to the console data that's in the root inorder.
            displayFaculty(root.right); // Recursively display right nodes.
        }
    }
}

Here's my Main.java file:

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        Student student1 = new Student("Mike", "Piazza", "S3123456");
        Student student2 = new Student("Jack", "Jill", "S3123456");
        Student student3 = new Student("Alice", "Jones", "S3123456");

        BinaryTree bt = new BinaryTree();
        bt.insertStudent(student1);
        bt.insertStudent(student2);
        bt.insertStudent(student3);
        bt.displayStudent(bt.root);
       }
     }

Here's my Student.txt file:

null null null null null null null

Here's the error I'm getting in the console:

Exception in thread "main" java.lang.NullPointerException
at BinaryTree.displayStudent(BinaryTree.java:118)
at BinaryTree.displayStudent(BinaryTree.java:107)
at BinaryTree.displayStudent(BinaryTree.java:107)
at Main.main(Main.java:13)
nampa
  • 1
  • 3
  • Not really a good example of a duplicate. Yes, it is a null pointer exception, but there are many ways to create those. They have created a bunch of null nodes and only checked if the parent nodes we're not null. – Glen Pierce May 11 '17 at 02:02
  • @GlenPierce This question was or will be resolved in a way unlikely to help future visitors. The more generic duplicate encompasses any future value that this question provides, thus closing it as a duplicate seems appropriate. If OP provided an [MCVE](https://stackoverflow.com/help/mcve) (the code seems much, much longer than it needs to be), they likely would've figured out the issue by themselves, but, if they didn't, the question would've had much greater future value than it does now, but then it would also presumably be much closer to the duplicate. – Bernhard Barker May 11 '17 at 10:51

1 Answers1

2

The reason it prints "null null null null null null" can be found in your displayStudent() method. You're asking to displayStudent(root.right), but you're setting those nodes to null in the constructors.

public Node(Student data) {
    this.data = data;
    this.left = null;
    right = null;
}

So when you go to display that data, you're running effectively displayStudent(null);

if(root != null) { // If root isn't empty. 
  displayStudent(root.left); // Recursively display left nodes. 
  System.out.println(root.data.toString()); // Print to the console data that's in the root in order.
  displayStudent(root.right); // Recursively display right nodes. 
}

I think you can fix this like this:

if(root != null) { // If root isn't empty.
  if(root.left != null){ 
      displayStudent(root.left); // Recursively display left nodes. 
  }
      System.out.println(root.data.toString()); // Print to the console data that's in the root in order.
  if(root.right != null){
      displayStudent(root.right); // Recursively display right nodes. 
   }
    }

The reason you're getting a null pointer exception is that you are not checking for null values before you call fw.write(root.data.toString());

Instead, I'd use a StringBuilder to add to a String that you write to file once, instead of inside each of the calls to your displayStudent(). I leave that as an exercise to the OP.

Random advice:
Having a binary tree that contains both Students and Faculty in the fashion you have is probably going to make you sad someday. I'd encourage you to have only one data type in the entire tree (possibly have Students and Faculty extend from some Abstract Class).

Glen Pierce
  • 4,401
  • 5
  • 31
  • 50
  • I genuinely appreciate your random advice. I will take it into consideration later on but first I simply want to write what's on the tree into a file. – nampa May 11 '17 at 01:42
  • I've updated my answer to include suggested fixes. – Glen Pierce May 11 '17 at 01:52
  • Thanks again, greatly appreciated. – nampa May 11 '17 at 02:02
  • If this works, please accept the answer, otherwise, let me know the results and I'll see if I can work it out. – Glen Pierce May 11 '17 at 02:04
  • That's not correct; when the code recurses the null pointer will be detected. The problem is further along at `for(int i = 0; i < 30; i++) { fw.write(root.data.toString());` - there is no guard to prevent accessing this when `root` is null. – Ken Y-N May 11 '17 at 02:58
  • @KenY-N, My entire answer did include comments about solving the null pointer exception specifically, but I don't think it was clear enough. I've edited my answer to more specifically call out the two problems: printing "null" and the null pointer exception so it's clearer. – Glen Pierce May 11 '17 at 05:30