← Unit 3 · all exercises
Saved in this browser only

A shopping cart

Write a Cart tracking a number of items and a total in cents, both starting at zero. add takes a price and increases both. itemCount and total return them, and averagePrice returns the total divided by the count as a double, or 0.0 for an empty cart.

class Cart { Cart(); void add(int price); int itemCount(); int total(); double averagePrice(); }

Cart.java
Loading editor…
Results

Examples

  • Cart c = new Cart(); c.add(100); c.add(200); c.total() → 300
  • Cart c = new Cart(); c.add(100); c.add(200); c.averagePrice() → 150

There are also 4 hidden tests you can't see. Solve the problem, not the examples.