Problem overview
The task is to build a VendingMachine class for a machine that sells one kind of item at a fixed price of 150. The machine remembers the money inserted so far, called the credit. A new machine has a credit of 0, and no constructor is needed because the fields have initial values. There are three methods:
insert(double amount)adds the amount to the credit and returns nothing.select()tries to buy an item and returns aString. If the credit is less than the price, it returns"Need N more", where N is the missing amount as a whole number, and the credit doesn't change. Otherwise it subtracts the price from the credit and returns"Dispensing!". Extra money stays in the credit, and an exact payment works.refund()returns the whole credit and sets it back to 0.
The driver inserts 50 and selects, inserts 150 more and selects, and then asks for a refund. It repeats with an exact 150, and then with 100:
Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100
After the first purchase the credit is 200 - 150 = 50, which is what the refund returns. After the exact payment the credit is 0.
Approach: methods that change and report state
An object has state, here credit and price, and methods that read or change it. Two of the three methods deliberately do different jobs with the same data. insert only changes the state. select changes it only on success and always reports the outcome as text.
The rule that matters most is when to subtract the price. A failed select must leave the credit alone, because the customer may insert more money and try again. So the early return for "not enough" comes first, and the subtraction sits below it where only a successful purchase reaches it.
refund has the opposite order problem. It must both return the credit and reset it to 0, but a method can't do something after its return statement. The solution first copies the credit into a local variable, then resets the field, then returns the copy.
Step by step
- Declare the class
VendingMachine. Each machine made from it keeps its own credit. - Add
private double credit = 0;, the money inserted so far. - Add
private double price = 150;, the cost of every item. - Declare
insertas public andvoid, taking adouble amount. - Add the amount to
creditwith+=, so earlier money isn't replaced. - Declare
selectas public, with no parameters, returningString. - Handle too little money. If
credit < price, return"Need ", the missing amount cast toint, and" more". Nothing is subtracted. - Subtract the price from
creditbelow theif. - Return
"Dispensing!". This line runs only when the credit covered the price. - Declare
refundas public, with no parameters, returningdouble. - Save the credit in a
doublenamedr. - Reset
creditto 0. - Return
r, the saved amount.
The solution in Java
class VendingMachine {
private double credit = 0;
private double price = 150;
public void insert(double amount) {
credit += amount;
}
public String select() {
if (credit < price) return "Need " + (int)(price - credit) + " more";
credit -= price;
return "Dispensing!";
}
public double refund() {
double r = credit;
credit = 0;
return r;
}
}
class Solution {
public void mainFunction() {
VendingMachine m = new VendingMachine();
m.insert(50);
System.out.println(m.select());
m.insert(150);
System.out.println(m.select());
System.out.println("Refunded: " + (int)m.refund());
m.insert(150);
System.out.println(m.select());
System.out.println("Refunded: " + (int)m.refund());
m.insert(100);
System.out.println(m.select());
System.out.println("Refunded: " + (int)m.refund());
}
}
Java details worth knowing:
- Field initializers.
private double credit = 0;sets the value when the object is created, sonew VendingMachine()works with the default constructor Java supplies. - Building the message.
"Need " + (int)(price - credit) + " more"joins aString, anintand anotherStringwith+. The cast turns thedouble100.0 into the whole number 100, so the text saysNeed 100 moreand notNeed 100.0 more. - The cast truncates. Casting a
doubletointdrops the fraction. With 100.5 inserted, the missing amount is 49.5 and the message isNeed 49 more. The lesson's driver only uses whole amounts. - The parentheses matter.
(int)(price - credit)casts the difference. Writing(int)price - creditwould cast onlypriceand leave adoublein the message. - The
ifwithout braces. A single statement after the condition is its body. The following lines are not part of it, so they run only when theifdidn't return.
Following the credit through the driver
The driver ends each round with a refund, so every round starts from a credit of 0. In the first round, 50 is inserted and select() reports the missing 100, leaving the credit at 50. Inserting 150 more raises it to 200, so the next select() dispenses and the credit falls to 50, which the refund returns. In the exact-payment round the credit goes 150, then 0, so the refund prints 0. In the last round, 100 is inserted and select() reports the missing 50 without touching the credit, so the refund returns the whole 100.
Edge cases and common mistakes
- Using
credit <= price. Exact payment must work, so the test is a strict<. - Subtracting the price before checking. The credit would drop even on a refused purchase, and the next refund would be wrong.
- Forgetting to subtract after a sale. The customer would get a second item for the same money, and the refund would return too much.
- Returning
creditinstead ofr. After the reset,creditis 0, so the refund would always be 0. - Repeated
selectcalls. With 300 inserted, the first two calls returnDispensing!, the third returnsNeed 150 more, and the followingrefund()returns0.0. - Asking twice for a refund. After inserting 100.5, the first
refund()returns100.5and a second one returns0.0.
