Shopping Cart in Java: Explanation & Practice

Create a simple shopping cart system

Problem summary

Create Item and Cart classes. Cart should track items and calculate total.

Starter code

// Create Item class with name and price
// Create Cart class with:
// - addItem(Item item)
// - double getTotal()
// - int getItemCount()

public class Main {
    public static void main(String[] args) {
        // Add items and print total
        // Print: Items: <count>, Total: lt;total>
    }
}

Expected output and test cases

  • 3 items totaling 45.5
    Items: 3, Total: $45.5
  • Single item
    Items: 1, Total: $100.0
  • Empty cart
    Items: 0, Total: $0.0

Hints

  1. Use ArrayList to store items
  2. Sum prices in getTotal()
  3. getItemCount() returns list size

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler