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
- Use ArrayList to store items
- Sum prices in getTotal()
- getItemCount() returns list size
Related OOP Basics exercises
- Practice Student Grade Calculator in Java
- Practice Bank Account Operations in Java
- Practice Circle Class in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler