CodeBlanks Logo Icon CodeBlanks

Cart design

Design the shopping cart class skeleton.

Project: Shopping cart

In this 5-lesson project you'll build a shopping cart. Each lesson adds one piece, and by the final lesson you'll have a complete app.

You'll use what you learned before:

  • dynamic list with ArrayList
  • for and for-each loops
  • output with System.out.println
  • decimals with double

You'll also learn cart.add, cart.set, cart.remove and tax calculation. Ready? Let's start.

The cart flow

The shopping cart works in three steps:

  1. Adding: an item is added to the cart.
  2. Listing: the items in the cart are shown.
  3. Total: the prices are summed.

In the first lesson we'll just define an empty cart (an ArrayList) and print it. The next lessons add item adding, total calculation and quantity updates. ArrayList grows automatically, so you don't need to know how many items will be added.

Practice Print the empty cart

Write a Main class with a main method. Assign new ArrayList<>() to ArrayList<String> cart. Print the cart with System.out.println(cart). Add import java.util.ArrayList; at the top.

Starter code

Main.java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Define the cart here
    }
}

Sample solution

Main.java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> cart = new ArrayList<>();
        System.out.println(cart);
    }
}

Expected output

[]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a shopping cart need first?

  • A list to hold items Correct answer
  • A database
  • A class
  • A file

Explanation: A cart uses a list to hold items.

2 Define the empty cart

Question
ArrayList<String> cart = new ____<>();
Answer
ArrayList<String> cart = new ArrayList<>();

Explanation: new ArrayList<>() defines the empty cart.

3 Match the cart steps

Term Meaning
Adding Item is placed in cart
Listing Items are shown
Total Prices are summed
ArrayList Cart type

All lessons in Beginner