Part 04 / Topic 10 of 10
Putting it together: a shopping cart preview
This previews the exercises' shopping cart. A fixed catalog (arrays) feeds a price lookup (HashMap), a growing cart (ArrayList) is scanned item by item, and a HashSet flags repeats — all four tools from this part, each doing the job it's best at.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
class ShoppingCartPreview {
public static void main(String[] args) {
// Catalog: a fixed, known-size list of items a Pune store sells.
// Known size up front, never grows at run time -> a plain array is a natural fit.
String[] catalogNames = {"Rice", "Dal", "Milk", "Sugar", "Tea"};
double[] catalogPrices = {1200.0, 450.0, 60.0, 55.0, 240.0};
// Build a HashMap once, so looking up a price later is instant
// (no scanning the two arrays item by item every time).
HashMap<String, Double> priceList = new HashMap<>();
for (int i = 0; i < catalogNames.length; i++) {
priceList.put(catalogNames[i], catalogPrices[i]);
}
// Cart: grows one scan at a time as Asha shops -> ArrayList is the natural fit.
ArrayList<String> cart = new ArrayList<>();
cart.add("Rice");
cart.add("Milk");
cart.add("Milk"); // scanned twice by mistake
cart.add("Tea");
// A HashSet answers "have I scanned this already?" in one lookup.
HashSet<String> alreadyScanned = new HashSet<>();
double total = 0.0;
System.out.println("--- Receipt ---");
for (String item : cart) {
double price = priceList.getOrDefault(item, 0.0);
total += price;
System.out.println(item + "\t₹" + price);
if (!alreadyScanned.add(item)) {
System.out.println(" (scanned again: " + item + ")");
}
}
System.out.println("---------------");
System.out.println("Total: ₹" + total);
System.out.println("Unique items in cart: " + alreadyScanned.size());
}
}
Output (examples/07_shopping_cart_preview.java):
--- Receipt ---
Rice ₹1200.0
Milk ₹60.0
Milk ₹60.0
(scanned again: Milk)
Tea ₹240.0
---------------
Total: ₹1560.0
Unique items in cart: 3
Notice priceList is built once, outside the scanning loop, from the two catalog arrays — building it fresh on every scan would waste the whole point of using a map. The full exercises build this further: quantities, a per-item receipt, and a discount rule.
Full program: examples/07_shopping_cart_preview.java.
Done here? The practice set for Part 4 — including the solutions — is on the part page.