Question

When I run my program it gives me this error. The errors are located in the MergeInventories class as well as the CombInv class. I have labeled them in the classes provided below.

java.lang.NullPointerException
    at CombInv.print(CombInv.java:19)
    at MergeInventories.main(MergeInventories.java:17)

I am simply trying to print out the data. My program essentially takes two arrays and MergeSorts them.

Here are the multiple classes of my program.

import java.io.*;

public class MergeInventories
{
    public static void main()
    {
        header();
        try
        {
            Inventory store1 = new Inventory(new File("F:\\M359 AP Computer Science\\JAVA\\Merge Inventories\\Store1.txt"));
            Inventory store2 = new Inventory(new File("F:\\M359 AP Computer Science\\JAVA\\Merge Inventories\\Store2.txt"));

            CombInv mergedInventory = mergeInventories(store1,store2);

            //store1.print();
            //store2.print();
            mergedInventory.print(); //********THIS IS LINE 17 OF THE ERROR*************
        }
        catch(Exception e)
        {
            e.printStackTrace();
            //System.out.print("Error.");
        }

    }

    private static CombInv mergeInventories(Inventory a, Inventory b)
    {
        CombInv inv = new CombInv();
        int i=0,j=0,k=0;

        while(i<a.size()&&j<b.size())
        {
            if(a.getProduct(i).getID() == b.getProduct(j).getID())
            {
                inv.add(new Product(a.getProduct(i).getID(),a.getProduct(i).getQty()+b.getProduct(j).getQty(),a.getProduct(i).getUP()));
                i++;
                j++;
            }
            else if(a.getProduct(i).getID() > b.getProduct(j).getID())
            {
                inv.add(b.getProduct(j));
                j++;
            }
            else
            {
                inv.add(a.getProduct(i));
                i++;
            }
            k++;
        }

        if(j<b.size())
        {
            for(j=j;j<b.size();j++)
            {
                inv.add(b.getProduct(j));
            }
        }
        else if(i<a.size())
        {
            for(i=i;i<a.size();i++)
            {
                inv.add(a.getProduct(i));
            }
        }
        return inv;
    }

    private static void header()
    {
        System.out.println("Varun Pinto \n8th Hour \nM359 AP Comp Sci \n");
    }
}

Then we have the Inventory class

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

public class Inventory
{
    protected int increment = -1;
    protected int size = 0;
    protected Product[] inventory = new Product[11];
    protected String header;
    protected static String CATEGORIES = "ID\tQTY\tU\\P";

    public Inventory()
    {
        header = "TOTAL INVENTORY";
    }

    public Inventory(File file)throws FileNotFoundException
    {
        Scanner fileScan = new Scanner(file);
        header = fileScan.nextLine();
        String throwaway = fileScan.nextLine();
        while(fileScan.hasNextLine())
        {
            Scanner lineScan = new Scanner(fileScan.nextLine());
            Product p = new Product(lineScan.nextInt(), lineScan.nextInt(), lineScan.nextDouble());
            increment+=1;
            inventory[increment]=p;
        }
    }

    public void add(Product p)
    {
        increment +=1;
        inventory[increment]=p;
        size +=1;
    }

    public Product getProduct(int i)
    {
        return inventory[i];    
    }

    public int size()
    {
        return size;
    }

    public void print()
    {
        System.out.println(header);
        System.out.println(CATEGORIES);
        for(Product p: inventory)
        {
            System.out.println(p.toString());
        }
        System.out.println();
    }
}

Next I have the CombInv class where one of the errors is located.

import java.text.*;

public class CombInv extends Inventory
{ 
    public void print(){

        System.out.println(header);
        System.out.println(CATEGORIES + "\tVALUE");

        double total = 0;

        NumberFormat f = NumberFormat.getNumberInstance();
        f.setMinimumFractionDigits(2);
        f.setMaximumFractionDigits(2);

        for(Product p: inventory)
        {
            System.out.println(p.toString() + "\t" + f.format(p.getQty() * p.getUP()));
//******THERE IS AN ERROR ON THE LINE ABOVE**************************
            total += p.getQty() * p.getUP();
        }

        System.out.println("Total Value of Stock:\t$" + total);
        System.out.println();
    }
}

Finally we have the Product class which is a basic superclass where I am trying to access .toString() but cannot.

import java.text.*;

public class Product
{
    private int idNum;
    private int quantity;
    private double unitPrice;

    public Product()
    {
        idNum = 0;
        quantity = 0;
        unitPrice = 0;
    }

    public Product(int id, int q, double price)
    {
        idNum = id;
        quantity = q;
        unitPrice = price;
    }

    public int getID()
    {
        return idNum;
    }

    public int getQty()
    {
        return quantity;
    }

    public double getUP()
    {
        return unitPrice;
    }

    public String toString()
    {
        NumberFormat f = NumberFormat.getNumberInstance();
        f.setMinimumFractionDigits(2);
        f.setMaximumFractionDigits(2);

        return idNum + "\t" + quantity + "\t" + f.format(unitPrice);
    }
}

Please be aware that the use of ArrayLists in the inventory do make this program work, however as this is a project I am NOT ALLOWED TO USE ARRAYLISTS only Arrays. Also I MUST use a MergeSort to sort the data.

Here are the two text files from which i read the data: Store1.txt

STORE 1 INVENTORY
ID  QTY U/P       
362 5   12.98
471 2   6.70
792 13  25.00
901 7   2.98

and Store2.txt

STORE 2 INVENTORY
ID  QTY U/P
163 4   7.20
209 5   11.98
471 5   6.70
608 4   5.90
627 2   9.99
792 1   25.00
812 4   6.00

Here is what I expect to be printed

My Name 
8th Hour 
M359 AP Comp Sci 

TOTAL INVENTORY                         //It only prints out
ID      QTY     U\P VALUE               //these two lines.
163     4       7.20    28.80
209     5       11.98   59.90
362     5       12.98   64.90
471     7       6.70    46.90
608     4       5.90    23.60
627     2       9.99    19.98
792     14      25.00   350.00
812     4       6.00    24.00
901     7       2.98    20.86
Total Value of Stock:   $638.94
Was it helpful?

Solution

It took me while to answer this because I essentially put it off for the longest time. The error is a NullPointerException and i fixed it with a simple addition of:

    if(p != null)

before all the instances in which I called the p.toString(). The answer is so simple I can't believe I lost my mind over it, all I had to do was check that the value wasn't a null and it would continue looping till it found actual values. I knew my Merge Sort worked. In the end it was a really simple fix and didn't require me to change the bulk my code at all.

Also, I had to increment size again in the while loop of the constructor method of the Inventory class. I forgot to do this, but my code worked, despite what people said about rewriting the MergeSorter!

OTHER TIPS

When you merge two sorted lists, perhaps you should consider using the following strategy:

  • Consider how large the resulting sorted list will be
  • Make your loop for the size of the resulting merged list
  • at each step consider which of the input lists elements should be used next
  • Make sure you handle an input list "running out" of elements

[Homework .. so no code supplied]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top