1

For a school assignment, we have to make a Shopping cart class, along with an Item class and a runner. I figured out how to print out a receipt for items the user enters, but one thing I can't figure out is how to write a sort method using insertion Sorting, which orders each item in the cart by its total cost (price * quantity)

Here is my error:

java.lang.NullPointerException
    at ShoppingCart.sort(ShoppingCart.java:54)
    at Shopping.main(Shopping.java:32)

I went back to the lines stated

ShoppingCart: (line 54)

public void sort() {
    double temp;
    int pos = 0;
    for (int i = 1;i< cart.length;i++){
      temp = cart[i].itemPrice(); //line 54
      pos = i;
      while (pos>0 && temp < cart[pos-1].itemPrice()) {
        cart[pos] = cart[pos-1];
        pos--;
      }
      cart[pos] = cart[i];
    }
  }

Shopping: (line 32)

 cart.sort();

And here is my method to get the price in the Item Class

public double itemPrice(){
     return total; }

I'm not sure how to fix the Null Pointer Exception error.

Joyce Pan
  • 13
  • 2

1 Answers1

2

I assume you've got something like this:

Item[] cart = new Item[50];

This creates an array that has room for 50 items.. but all that room is initialized to null. You still have to make 50 items:

for (int i = 0; i < cart.length; i++) cart[i] = new Item();
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • Thank you so much! I realized that I made a new array every 5 items, so not every space was filled with a value - which is why I made a numObjects variable previously, but I didn't use it. – Joyce Pan Feb 28 '19 at 00:32