Java Bootcamp – Workbooks and Challenges
)}

Shopping Cart – Part 3

In this workbook, you will apply the Big 3 steps to the Cart class.

Requirements

The fields and actions for this class are as follows:

  • Fields: items.

  • Actions: add(), remove(), and checkout().

Task 1 – Add the field


The elements in items can increase or decrease. So, make items an ArrayList.

Task 2 – The Big 3


  • Constructor

    • receives no parameters.

    • sets the field equal to a new object of the ArrayList class.

  • Getter: getItem

    • receives one parameter: int index.

    • returns an object at the requested index.

  • Setter: setItem

    • receives two parameters: int index, Item item.

    • sets an element equal to a copy of the object being passed in.

As you're applying each step, careful not to fall into the reference trap.

Task 3 – add


The user can only add an item to the cart if it wasn't already added.

Hint: The ArrayList class has a contains() method. contains() returns true if the ArrayList already "contains" the element.

 /**
  * Name: add
  * @param item
  * @return boolean
  *
  * Inside the function:
  *   1. Adds an item to the cart if it wasn't already added.
  */

Task 4 – remove.


/**
 * Name: remove
 * @param name
 *
 * Inside the function:
 *   1. Removes the item that matches the name passed in.
 */

Task 5 – checkOut.


/**
 *  Name: checkout
 *  @return (String)
 *
 *  Inside the function:
 *   1. Calculates the subtotal (price before tax).
 *   2. Calculates the tax (assume tax is 13%).
 *   3. Calculates total: subtotal + tax
 *   4. Returns a String that resembles a receipt. See below.
 */

The 4th step will return a receipt that adheres to this format:

        "\tRECEIPT\n\n" +
        "\tSubtotal: $" + <subtotal> + "\n" +
        "\tTax: $" + <tax> + "\n" +
        "\tTotal: $" + <total> + "\n";

Task 6 – toString.


  • Set a String variable temp that equals "".

  • Loop through every item in the items field.

  • During each run, add the toString of each item.

  • During each run, add one line \n to temp.

  • return temp;

Task 7 – Testing the code


Inside Main, create an object of the Cart class. Then, add four items to the shopping cart.

cart.add(new Item("Celery", 0.99));

cart.add(new Item("Celery", 0.99));

cart.add(new Item("Spinach", 0.99));

cart.add(new Item("Coriander", 1.29));

Print the cart. It should only display three items because the first two are duplicates.

It shows four!? Why didn't the contains() method work?

Find out in Part 4.

Feedback Summary
4.8
39 students
5

92%
4

3%
3

0%
2

0%
1

5%
Written Reviews
There are no written reviews yet.