THINK FIRST·CODE LATER

← All labs

Shopping cart with an ArrayList

Problem

Write a class CartItem (name, price, quantity, addQuantity, subtotal, toString formatted %-10s %2d x %6.2f = %7.2f) and a public class ShoppingCart that keeps an ArrayList<CartItem>.

Commands until the end of input:

  • add NAME PRICE QTY — adding a product already in the cart (ignore case) increases its quantity instead of adding a second line;
  • remove NAME — prints removed Tea or not in cart: Tea;
  • show — prints every item and 3 products, 7 units, total 58.40.

Write a helper int indexOf(ArrayList<CartItem> cart, String name).

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l13-3-data-1.txt

add Tea 12.5 2 add Bread 8 1 add tea 12.5 1 show
What your program must print for l13-3-data-1.txt
Tea         3 x  12.50 =   37.50
Bread       1 x   8.00 =    8.00
2 products, 4 units, total 45.50

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l13-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content l13-3-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.