john baker
john baker

Reputation: 1

How to fix a loop for a heap structure

The code compiles but when you run it an error message occurs that gives a null pointer exception. As SEEN in the bottom. the code is supposed to read text from a txt file that is inputted in the program and then create a new txt file with the content of the first txt file sorted by years of service. However, i keep receiving that error message. Any help would be greatly appreciated. I added the error message at the bottom thank you to everyone who is helping your time and effort is greatly appreciated :)

(25 points)Define a Java class called Employee. The class has data members and accompanying accessor and mutator methods for each of the following six data items. (This involves creating the file Employee.java.)

(50 points)‘Heap’ is a tree-based data-structure that satisfies the heap property. A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node.

By having a heap (or an array that satisfies the heap property), it would be more efficient (generally faster) to perform important tasks on the array such as finding the maximum element in the array (and removing it) and sorting the array.

In this assignment, you will have to write a program that reads a list of employees from a file. The name of the file will be ‘Employee.txt’. The program should output the sorted array to a file called “SortedEmployee.txt” Heapsort code:

public class HeapSort
{

   //heap sort method
   public static <Employee extends Comparable<Employee>> void heapSort(Employee[] list)
   {
      //create a Heap of integers
      Heap<Employee> heap = new Heap<>();

      //add elements to the heap
      for (int i = 0; i< list.length; i++)
         heap.add(list[i]);

      //remove elements from the heap
      for(int i = list.length - 1; i >= 0; i--)
         list[i] = heap.remove();
   }


}  

Heap code:

import java.util.ArrayList;

public class Heap<Employee extends Comparable<Employee>>
{  
   private ArrayList<Employee> list = new ArrayList<>();

   public Heap(){}

   public Heap(Employee[] objects)
   {
      for(int i = 0; i < objects.length; i++)
         add(objects[i]);
   }
   public void add(Employee newObject)
   {
      list.add(newObject);
      int currentIndex = list.size() - 1;

      while(currentIndex > 0)
      {
         int parentIndex = (currentIndex -1)/2;
         if(list.get(currentIndex).compareTo(list.get(parentIndex)) > 0)
         {
            Employee temp = list.get(currentIndex);
            list.set(currentIndex, list.get(parentIndex));
            list.set(parentIndex, temp);
         }
         else
            break;

         currentIndex = parentIndex;
      }
   }
   public Employee remove()
   {
      if(list.size() == 0) return null;

      Employee removeObject = list.get(0);
      list.set(0, list.get(list.size() -1));
      list.remove(list.size() -1);

      int currentIndex = 0;
      while(currentIndex < list.size())
      {
         int leftChildIndex = 2 * currentIndex + 1;
         int rightChildIndex = 2 * currentIndex + 2;
         if(leftChildIndex >= list.size()) break;
         int maxIndex = leftChildIndex;
         if(rightChildIndex < list.size())
         {
            if(list.get(maxIndex).compareTo(list.get(rightChildIndex)) < 0)
               maxIndex = rightChildIndex;
         }
         if(list.get(currentIndex).compareTo(list.get(maxIndex)) < 0)
         {
            Employee temp = list.get(maxIndex);
            list.set(maxIndex, list.get(currentIndex));
            list.set(currentIndex, temp);
            currentIndex = maxIndex;
         }
         else
            break;   
      }
      return removeObject;
    }
    public int getSize()
    {
      return list.size();
    }

    public void print()
    {
      for (int i = 0; i <= getSize()-1; i++)
      {
         System.out.print("Index: " + i + " Data: " + list.get(i));

         System.out.println();
      }
    } 
}

Employee Object Class:

public class Employee implements Comparable<Employee>
{
   private String id;
   private String name;
   private double salary;
   private String department;
   private String position;
   private int yos;
   public Employee(String id, String name, double salary,String department,String position,int yos)
   {
      this.id = id;
      this.name = name;
      this.salary = salary;
      this.department = department;
      this.position = position;
      this.yos = yos;
   }
   public void setid(String id)
   {
      this.id = id;
   }
   public void setname(String name)
   {
      this.name = name;
   }
   public void setsalary(double salary)
   {
      this.salary = salary;
   }
   public void setdepartment(String department)
   {
      this.department = department;
   }
    public void setposition(String position)
   {
      this.position = position;
   }
   public void setyos(int yos)
   {
      this.yos = yos;
   }
   public String getid()
   {
      return id;
   }
   public String getname()
   {
      return name;
   }
    public double getsalary()
   {
      return salary;
   }
    public String getdepartment()
   {
      return department;
   }
   public String getposition()
   {
      return position;
   }
    public int getyos()
   {
      return yos;
   }
   public int compareTo(Employee emp)
   {
      return (this.yos - emp.yos);
   }
   public String toString()
   {
      return "ID=" + this.id+ ", name=" + this.name+ ", salary= $" + this.salary+ ", department:" + this.department+ ", postion:" + this.position+ ",yos= $" + this.yos + "]\n";
   }
}

Demo code:

 import java.util.*;
import java.io.*;


public class EmployeeDemo
{
   public static void main(String[] args)throws IOException
   {
      Employee[] list = new Employee[5];
         Scanner keyboard = new Scanner(System.in);

         System.out.println("Please enter the text file: ");
         String fileName = keyboard.nextLine();

         File myFile = new File(fileName);
         Scanner inputFile = new Scanner(myFile);

      //Read all of the values from the file
      //and calculate their total


         //Read a value from the file
         String id = inputFile.nextLine();
         String name = inputFile.nextLine();
         double salary = inputFile.nextDouble();
         String clear = inputFile.nextLine();
         String department = inputFile.nextLine();
         String position = inputFile.nextLine();
         int yrService = inputFile.nextInt();
         String llear = inputFile.nextLine();

         list[0] = new Employee(id,name,salary,department,position,yrService);






      //close the file


     // File o = new File("SortedEmployee.txt");
        //o.createNewFile();
      System.out.println("Enter the file name to be transfered to: ");
      String filename = keyboard.nextLine();
      PrintWriter outputFile = new PrintWriter(filename);//dont need the top


      //HeapSort<Employee> h = new heapSort<Employee>(Employee);
      HeapSort.heapSort(list);

      //Display the sum of the numbers
      while(inputFile.hasNext())//this loop is wrong too
      {

         outputFile.println(list[0].toString());

      }
      outputFile.close();
       inputFile.close();
      System.out.print("File Sorted and Transferred");

   }
}

here is the error message i am receiving:

Please enter the text file: 
C:\Users\jose385\Desktop\Employee.txt
Enter the file name to be transfered to: 
green
Exception in thread "main" java.lang.NullPointerException
    at Heap.add(Heap.java:22)
    at HeapSort.heapSort(HeapSort.java:13)
    at EmployeeDemo.main(EmployeeDemo.java:50)

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

Upvotes: 0

Views: 586

Answers (1)

Scary Wombat
Scary Wombat

Reputation: 44813

You make the List have a size of 5

Employee[] list = new Employee[5];

but only add one element

list[0] = new Employee(id,name,salary,department,position,yrService);

Actually what is the point of only sorting one element

Also try to follow a tutorial on the correct way to implement Comparable

Upvotes: 1

Related Questions