← Unit 3 · all exercises
Saved in this browser only

A vending machine

Write a Vending machine holding a price and the money inserted so far, starting at 0. insert adds money. canBuy returns whether enough has been inserted. change returns how much would come back, or 0 when there is not enough.

class Vending { Vending(int price); void insert(int amount); boolean canBuy(); int change(); }

Vending.java
Loading editor…
Results

Examples

  • Vending v = new Vending(150); v.insert(200); v.change() → 50
  • Vending v = new Vending(150); v.insert(100); v.canBuy() → false

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