3 Replies - 7286 Views - Last Post: 13 March 2011 - 08:45 PM Rate Topic: ***-- 2 Votes

#1 Breana  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 13-March 11

Shopping Cart Won't Add Items or print in driver class

Posted 13 March 2011 - 03:25 PM

Hello. I am relatively new to Java and I've have been able to get the following program to compile, but when I attempt to run the driver (Shopping.java), the items that I create are never added to the toString that I'm attempting to print underneath my Menu in Shopping.java. Can you help me figure out why the items aren't added to my Shopping Cart?

This is the prompt that my instructor gave me:
In this exercise you will complete a class that implements a shopping cart as an array of items. The file Item.java contains the definition of a class named Item that models an item one would purchase. An item has a name, price, and quantity (the quantity purchased). The file ShoppingCart.java implements the shopping cart as an array of Item objects.

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. (I'm using a switch method instead because I'm stubborn and already started doing it this way and don't want to start over) 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.

Shopping.java (my driver):

//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.

import java.util.Scanner;
import java.text.NumberFormat;
public class Shopping
{
    static Scanner scan = new Scanner(System.in);
    static NumberFormat fmt = NumberFormat.getCurrencyInstance();

    static ShoppingCart cart = new ShoppingCart();
    static int totalQuantity = 0;
    static double totalPrice = 0;
    static int itemCount = 0;

    public static void main(String[] args)
    {
        System.out.println("Hello, welcome to the grocery store!");
        printMenu();
        int choice = scan.nextInt();
        while (choice != 0)
        {
            dispatch(choice);
            printMenu();
            choice = scan.nextInt();
        }
        System.out.println("Please pay $"+ totalPrice);
    }

    public static void dispatch(int choice)
    {
        int loc;
        switch(choice)
        {
            case 0: 
            System.out.println("Please pay $"+ totalPrice);
            break;

            case 1:
            System.out.print("Item Name: ");
            String itemName = scan.next();

            System.out.print("Price: $");
            double price = scan.nextDouble();

            System.out.print("Quantity: ");
            int quantity = scan.nextInt();
            totalQuantity =+ quantity;
            totalPrice +=(quantity*price);
            itemCount += 1;
            cart.addToCart(itemName, price, quantity);
            break;

            default:
            System.out.println("Sorry, invalid choice");

        }
    }

    public static void printMenu()
    {
        System.out.println("\n   Menu   ");
        System.out.println("   ====");
        System.out.println("0: Check Out");
        System.out.println("1: Pick a new item");
        System.out.println(cart.toString());
        System.out.print("\nEnter your choice: ");
    }

}


ShoppingCart.java:

// **********************************************************************
//   ShoppingCart.java
//
//   Represents a shopping cart as an array of items
// **********************************************************************

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
    //Declare an instance variable cart to be an array of Items and instantiate cart in the constructor to be an array holding capacity Items.
    private Item[] cart = new Item[capacity];
    // -----------------------------------------------------------
    //  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.
    //  Add the item to the cart and update the totalPrice instance variable (note this variable takes into account the quantity).
    // -------------------------------------------------------
 

    public void addToCart(String itemName, double price, int quantity)
    {
        if (itemCount == capacity)
        {
            increaseSize();
            cart[itemCount] = new Item(itemName, price, quantity);
            totalPrice += (totalPrice * quantity);
            itemCount++;
        }
    } 

    // -------------------------------------------------------
    //  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.java:

// ***************************************************************
//   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;
    }
} 




Thank you!


Is This A Good Question/Topic? 0
  • +

Replies To: Shopping Cart Won't Add Items or print in driver class

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10805
  • View blog
  • Posts: 40,278
  • Joined: 27-December 08

Re: Shopping Cart Won't Add Items or print in driver class

Posted 13 March 2011 - 06:18 PM

There are a few things regarding your ShoppingCart class. First, in your addToCart() method, you only add the Item to the array if there is no more space in the array. You only want to increaseSize() if the array is full.

Second, you instantiate your array outside the constructor. At that point, capacity = 0. You want to instantiate your array inside the constructor after you initialize capacity to 5.
Was This Post Helpful? 1
  • +
  • -

#3 Breana  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 13-March 11

Re: Shopping Cart Won't Add Items or print in driver class

Posted 13 March 2011 - 08:33 PM

View Postmacosxnerd101, on 13 March 2011 - 05:18 PM, said:

There are a few things regarding your ShoppingCart class. First, in your addToCart() method, you only add the Item to the array if there is no more space in the array. You only want to increaseSize() if the array is full.

Second, you instantiate your array outside the constructor. At that point, capacity = 0. You want to instantiate your array inside the constructor after you initialize capacity to 5.


Thank you so much!! That helped me get it working right away. I've been stressing over this program for a few weeks now and each time I've looked at it, I always walked away angry.
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10805
  • View blog
  • Posts: 40,278
  • Joined: 27-December 08

Re: Shopping Cart Won't Add Items or print in driver class

Posted 13 March 2011 - 08:45 PM

Glad I could help! :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1