简体   繁体   中英

Shopping Cart Java Application (addToCart)

I am doing a Java Application for a class and need help with errors that are coming up after running the app.

The app is supposed to allow the user to add an item to the shopping cart(item name, price, quantity). The user described item will be added to the shopping cart array, and then it will be printed out once it is successfully added.

The shopping cart has a max capacity of 5 items initially, but if the cart size is > 5, it will be increased + 3, via the increaseSize method.

As stated below, I believe that the addToCart method is not adding the user described item to the cart. That is why it is a null value within the toString method.

So, I basically need help with the addToCart method. Please correct me if I am wrong. Thank you.

An output from running the app is as follows:

run:
Enter the name of the item: a
Enter the unit price: 2
Enter the quantity: 2
Exception in thread "main" java.lang.NullPointerException
    at shop.ShoppingCart.toString(ShoppingCart.java:62)
    at java.lang.String.valueOf(String.java:2854)
    at java.io.PrintStream.println(PrintStream.java:821)
    at shop.Shop.main(Shop.java:49)
Java Result: 1

Below is the ShoppingCart Class.

The toString method should not have any errors being produced, but I believe that the problem lies within the addToCart method.

// **********************************************************************
//   ShoppingCart.java
//
//   Represents a shopping cart as an array of items
// **********************************************************************
import java.text.NumberFormat;

public class ShoppingCart
{

    private Item[] cart;
    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

    // -----------------------------------------------------------
    //  Creates an empty shopping cart with a capacity of 5 items.
    // -----------------------------------------------------------
    public ShoppingCart()
    {

      capacity = 5;
      cart = new Item[capacity];
      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);
        itemCount += quantity;
        cart[itemCount] = temp;
        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[capacity+3];
        for(int i=0; i < capacity; i++)
        {
            temp[i] = cart[i];
        }
        cart = temp; 
        temp = null;
        capacity = cart.length;
    }
}

Below is the Shop Main.

The ArrayList is not in use at this time, but will be later once the toString errors are corrected.

package shop;

// ***************************************************************
//   Shop.java
//
//   Uses the Item class to create items and add them to a shopping
//   cart stored in an ArrayList.
// ***************************************************************

import java.util.ArrayList;
import java.util.Scanner;

public class Shop
{
    public static void main (String[] args)
    {
      ArrayList<Item> cart = new ArrayList<Item>();

      Item item;
      String itemName;
      double itemPrice;
      int quantity;

      Scanner scan = new Scanner(System.in);

      String keepShopping = "y";
      ShoppingCart cart1 = new ShoppingCart();
      do
          {
            System.out.print ("Enter the name of the item: ");
            itemName = scan.next();

            System.out.print ("Enter the unit price: ");
            itemPrice = scan.nextDouble();

            System.out.print ("Enter the quantity: ");
            quantity = scan.nextInt();

            // *** create a new item and add it to the cart
            cart1.addToCart(itemName, itemPrice, quantity);



            // *** print the contents of the cart object using println
            System.out.println(cart1);

            System.out.print ("Continue shopping (y/n)? ");
            keepShopping = scan.next();
          }
      while (keepShopping.equals("y"));

    }
}

Below is the Item Class:

package shop;

// ***************************************************************
//   Item.java
//
//   Represents an item in a shopping cart.
// ***************************************************************

import java.text.NumberFormat;

public class 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;
    }
} 

I believe the problem is caused by these two lines from addToCart() :

itemCount += quantity;
cart[itemCount] = temp;

Unless quantity is 0 , this means cart[0] will never contain anything. In fact, whatever the value of quantity , you will be leaving that many gaps in cart (eg if quantity is 2, cart[0] and cart[1] will be null).

Since an Item already includes the quantity, I believe you meant to do this:

cart[itemCount] = temp;
itemCount += 1;

This way the first item will be put in cart[0] , the second in cart[1] , and so on.

Another small piece of advice: if you are concatenating any object with a String, you don't need to call toString() on the object. Java will automatically call String.valueOf() on the object, which avoids a NullPointerException because it returns the String "null" instead. In this case, it might have helped you debug the problem because you would have noticed the null String appearing in your output. You would have to change your code to the following:

for (int i = 0; i < itemCount; i++)
    contents += cart[i] + "\n";
public void addToCart(String itemName, double price, int quantity)
{ 

    Item temp = new Item(itemName, price, quantity);
    totalPrice += (price * quantity);
    itemCount += quantity;
    cart[itemCount] = temp;
    if(itemCount==capacity)
    {
        increaseSize();
    }
}

This code is broken. You try to add to cart at index itemCount . This will throw index out of bound execptions. basicly you increase the size of your cart to late.

This also causes a lot off empty places in your array. You do not add your next Item at the next place of your arra but you jump quantity places ahead. This causes some of the values in your array to be null . This is most likly causing the NullPointerExceütion in toString() .

For how to implement this self growing list. You might want to take a look at the class ArrayList that comes with the JDK.

there are some other points i want to point out:

  • google javaDoc and use it instead of your own custom comments
  • replace your for-loop in toString() with a for-each-loop

The problem lies both in your addToCart method. If you type this code:

ShoppingCart shopcart= new ShoppingCart();
shopcart.addToCart("foo", 3, 2);

The shopping cart will have the following attributes:

totalPrice=6
itemCount = 2;
cart = { null, null, foo, null, null};

The problem is that addToCart only modify the "itemcount" element of the array cart without considering the number of element added. Moreover, cart[0] will stay at null forever. You should remplace theses lines itemCount += quantity; cart[itemCount] = temp;

by

for ( int i =0 ; i<quantity;i++)
{
     cart[itemCount+i] = temp;
} 
itemCount += quantity;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM