Cart design
- Java course
- Beginner
- Lesson 48/116
- 6 min
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 forandfor-eachloops- 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:
- Adding: an item is added to the cart.
- Listing: the items in the cart are shown.
- 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
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Define the cart here
}
}Sample solution
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
ArrayList<String> cart = new ____<>();
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 |