Java Shopping Cart Array List (method addToCart not working)

时间:2018-02-01 18:22:42

标签: java arrays

I am working on an assignment for my computer science class where I create a program that simulates grocery shopping by creating a class that implements a shopping cart as an array of items. The tasks I must complete are as follows:

  1. Complete the ShoppingCart class by doing the following: a. Declare an instance variable cart to be an array of Items and instantiate cart in the constructor to be an array holding capacity Items. b. Fill in the code for the increaseSize method. Your code should be similar to that in Listing 7.8 of the text but instead of doubling the size just increase it by 3 elements. c. Fill in the code for the addToCart method. This method should add the item to the cart and update the totalPrice instance variable (note this variable takes into account the quantity). d. Compile your class.

  2. Write a program that simulates shopping. The program should have a loop that continues as long as the user wants to shop. Each time through the loop read in the name, price, and quantity of the item the user wants to add to the cart. After adding an item to the cart, the cart contents should be printed. After the loop print a "Please pay ..." message with the total price of the items in the cart.

At the moment I am stuck on the addToCart method. When I run the program it will allow input for the first item's information but then it displays the error "java.lang.NullPointerException" and stops working. What should I do to get my code to work properly? I would really appreciate some help with this. :)

Here is my code:

Shopping Cart import java.text.NumberFormat; public class ShoppingCart { private int itemCount; // total number of items in the cart private double totalPrice; // total price of items in the cart

    private int capacity; // current cart capacity

    Item[] cart;
    // -----------------------------------------------------------
    // Creates an empty shopping cart with a capacity of 5 items.
    // -----------------------------------------------------------
    public ShoppingCart()
    {
        capacity = 5;
        itemCount = 0;
        totalPrice = 0.0;
    }
    // -------------------------------------------------------
    // Adds an item to the shopping cart.
    // -------------------------------------------------------
    public void addToCart(String itemName, double price, int quantity)
    {
        Item temp = new Item(itemName, price, quantity);
        totalPrice += (price * quantity);
        for ( int i = 0 ; i < quantity; i++)
        {
             cart[itemCount + i] = temp;
        } 
        itemCount += quantity;
        if(itemCount==capacity)
        {
            increaseSize();
        }
    }
    // -------------------------------------------------------
    // Returns the contents of the cart together with
    // summary information.
    // -------------------------------------------------------
    public String toString()
    {
        NumberFormat fmt = NumberFormat.getCurrencyInstance();

        String contents = "\nShopping Cart\n";
        contents += "\nItem\t\tUnit Price\tQuantity\tTotal\n";

        for (int i = 0; i < itemCount; i++)

            contents += cart[i].toString() + "\n";

        contents += "\nTotal Price: " + fmt.format(totalPrice);
        contents += "\n";

        return contents;
    }
    // ---------------------------------------------------------
    // Increases the capacity of the shopping cart by 3
    // ---------------------------------------------------------
    private void increaseSize()
    {
        Item[] temp = new Item[cart.length + 3];

        for (int num = 0; num < cart.length; num++)
        {
         temp[num] = cart[num];
         cart = temp;
        }
    }
}

Item

import java.text.NumberFormat;
public class Item implements Comparable<Item>
{
    private String name;
    private double price;
    private int quantity;

    // -------------------------------------------------------
    // Create a new item with the given attributes.
    // -------------------------------------------------------
    public Item (String itemName, double itemPrice, int numPurchased)
    {
        name = itemName;
        price = itemPrice;
        quantity = numPurchased;
    }

    // -------------------------------------------------------
    // Return a string with the information about the item
    // -------------------------------------------------------
    public String toString ()
    {
        NumberFormat fmt = NumberFormat.getCurrencyInstance();

        return (name + "\t" + fmt.format(price) + "\t" + quantity + "\t"
        + fmt.format(price*quantity));
    }

    // -------------------------------------------------
    // Returns the unit price of the item
    // -------------------------------------------------
    public double getPrice()
    {
        return price;
    }

    // -------------------------------------------------
    // Returns the name of the item

    // -------------------------------------------------
    public String getName()
    {
        return name;
    }

    // -------------------------------------------------
    // Returns the quantity of the item
    // -------------------------------------------------
    public int getQuantity()
    {
        return quantity;
    }

    public int compareTo(Item other)
    {
        if(this.getPrice()*getQuantity() > other.getPrice()*other.getQuantity())
            return 1;
        else if (this.getPrice()*this.getQuantity() < other.getPrice()*other.getQuantity())
            return -1;
        else
            return 0;
    }
}

Shopping

    //Simulates shopping by using the ShoppingCart and Item classes
import java.util.Scanner;
public class Shopping

{
    public static void main(String[] args)
    {
        ShoppingCart cart = new ShoppingCart();

        String keepShopping;
        Item item;
        String itemName;
        double itemPrice;
        double totalPrice = 0;
        int quantity;

        Scanner scan = new Scanner(System.in);
        do
        {
            System.out.println("Enter the name of the item");
            itemName = scan.next();
            System.out.println("Enter the item's price");
            itemPrice = scan.nextDouble();
            System.out.println("Enter the quantity of the item");
            quantity = scan.nextInt();

            totalPrice = (itemPrice * quantity);

            cart.addToCart(itemName, itemPrice, quantity);
            System.out.println(cart.toString());

            System.out.println("Would you like to continue shopping "
                + "(y/n)?");
            keepShopping = scan.next();
        }
        while (keepShopping.equalsIgnoreCase("y"));

        System.out.println("Please pay $" + totalPrice);
    }

2 个答案:

答案 0 :(得分:1)

You are not intializing the variable cart

Try using cart = new Item[capacity]; Or something like that.

If your capacity can increase at a certain point why don't you change the variable cart to an arrayList ?

Like this :

List <Item> cart = new ArrayList<Item> ();

And in the method addToCart just use add in your loop like this : cart.add(temp);

Edit: you will have to import the corresponding Interface :

import java.util.ArrayList;

import java.util.List;

答案 1 :(得分:0)

In your ShoppingCart class you never initialize your Item Array so it is null, so when you try and add something to that array you get the null pointer exception.

To fix this do something like this in your constructor

 public ShoppingCart()
{
    capacity = 5;
    itemCount = 0;
    totalPrice = 0.0;
    //Does not have to be 10. Could be any number.
    //Just makes sure to not go over 10 or you will have to use your increaseSize method
    cart = new Item[10]
}

If you want to be fancy you could also do something like this (This is probably better)

 public ShoppingCart(int size)
{
    capacity = 5;
    itemCount = 0;
    totalPrice = 0.0;
    cart = new Item[size]
}