A Shopping Cart Using the ArrayList Class

In this exercise you will implements a shopping cart using the ArrayList class. 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 Shop.java is an incomplete program that models shopping.

  1. Complete Shop.java as follows:
    1. Declare and instantiate a variable cart to be an empty ArrayList.
    2. Fill in the statements in the loop to add an item to the cart and to print the cart contents (using the default toString in the ArrayList class). Comments in the code indicate where these statements go.
    3. Compile your program and run it.

  2. You should have observed two problems with using the default printing for the cart object. The output doesn't look very good and the total price of the goods in the cart is not computed or printed. Modify the program to correct these problems by replacing the print statement with a loop that does the following:
    1. Gets each item from the cart and prints the item.
    2. Computes the total price of the items in the cart (you need to use the getPrice and getQuantity methods of the Item class). The total price should be printed after the loop.

  3. Compile and run your program.

Go back to lab2 index page