Problem overview
You build a VendingMachine class for a machine that sells one kind of item at a fixed price of 150. It keeps the money inserted so far, the credit, sells an item when the credit is enough, and gives the remaining credit back on request. A new machine is made with VendingMachine() and starts with credit 0.
insert(amount: Double): Unitaddsamountto the credit. It prints and returns nothing.select(): Stringtries to buy one item. 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 does not change. Otherwise it subtracts the price from the credit and returns"Dispensing!". Any extra money stays in the credit, and exact payment works.refund(): Doublereturns the whole credit and sets it back to 0.
In the driver, 50 is inserted and the machine answers Need 100 more. After another 150 the credit is 200, so it dispenses and keeps 50, and the refund is 50. Then 150 is an exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100:
Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100
Approach: an object that remembers its state
The credit has to survive between calls: insert changes it, and select and refund read it later. That is what a class is for. Each machine object has its own credit field, so two machines never share money. The field is a private var: private so that only the machine's own methods change it, and var because it changes over time.
The key rule is in select. A failed purchase only reports what is missing and must not touch the credit. A successful one subtracts exactly the price, no more, so leftover money stays available for another purchase or a refund. The comparison is less than, which makes a credit equal to the price a success.
Step by step
- Declare the class
VendingMachineto hold the state and the actions on it. - Add
private var credit = 0.0. The literal0.0makes Scala infer the typeDouble, so no annotation is needed. A new machine holds no money. - Add
private var price = 150.0. Every item costs 150. It is avarin the lesson even though nothing changes it. - Write the header of
insertwith aDoubleparameteramountand the result typeUnit. - Add
amounttocreditwith+=. Add to what is already there; replacing it would lose earlier coins. - Write the header of
select, with no parameters and aStringresult. - Handle too little money. If
credit < price, return"Need " + (price - credit).toInt + " more". ThetoIntturns the missing amount into a whole number by dropping the decimals, so 100.0 prints as100, not100.0. Thereturnsits inside the braces of a one-lineif, and the credit is untouched. - Subtract the price from the credit. Only a successful purchase reaches this line.
- Return
"Dispensing!". - Write the header of
refund, with no parameters and aDoubleresult. - Save the credit in a
valnamedr. Once the credit is reset, the old value would be gone. - Reset
creditto 0.0. - Return
r, the saved money.
The solution in Scala
class VendingMachine {
private var credit = 0.0
private var price = 150.0
def insert(amount: Double): Unit = {
credit += amount
}
def select(): String = {
if (credit < price) { return "Need " + (price - credit).toInt + " more" }
credit -= price
return "Dispensing!"
}
def refund(): Double = {
val r = credit
credit = 0.0
return r
}
}
class Solution {
def mainFunction(): Unit = {
val m = VendingMachine()
m.insert(50.0)
println(m.select())
m.insert(150.0)
println(m.select())
println("Refunded: " + m.refund().toInt)
m.insert(150.0)
println(m.select())
println("Refunded: " + m.refund().toInt)
m.insert(100.0)
println(m.select())
println("Refunded: " + m.refund().toInt)
}
}
Scala details
- Mixing a
Stringand numbers with+."Need " + (price - credit).toInt + " more"works becauseString's+converts the number to text. The parentheses make the subtraction happen first. toInttruncates. It cuts off the fraction instead of rounding. With a credit of 100.5, the missing 49.5 becomes 49, so the message isNeed 49 more. WithouttoInt, the message would readNeed 49.5 more, and for whole amountsNeed 100.0 more, which doesn't match the expected output.- Inferred types.
private var credit = 0.0has no written type, and Scala infersDoublefrom the value. Writing0instead would inferIntand make the later+= amountwith aDoublefail to compile. returnand result types. The methods that usereturnhave their result types written, as Scala requires for them.- The driver's
.toInt.refund()returns aDouble, which would print as50.0. The driver converts it to print50.
Edge cases and common mistakes
- Exact payment. A credit of exactly 150 must dispense. Using
credit <= priceas the failure test would refuse it. The check is strictly less than. - Forgetting to subtract the price. The machine would dispense but keep the credit, and the refund would be too large. In the driver, the first refund would be 200 instead of 50.
- Subtracting on a failed purchase. Subtract only after the check passes. A failed
selectmust leave the credit exactly as it was. - Returning
creditafter resetting it. Ifrefundsetscredit = 0.0and then returnscredit, it always returns 0. The saved valueris what you return. - Asking for a refund twice. The second call returns 0, because the first one reset the credit.
- Several purchases in a row. With 300 inserted, the first two
select()calls dispense, and the third returnsNeed 150 more, since the credit is back to 0.
Testing
Try these on a new machine:
select()right away returnsNeed 150 more.- Insert 100.5, then
select():Need 49 more.refund()then returns 100.5, and a secondrefund()returns 0.0. - Insert 150 twice: two
select()calls dispense, and the third returnsNeed 150 more.
Key takeaways
- A class keeps state in private fields that its methods read and change.
- Check the failure case first, and change the state only on success.
- Save a value in a local
valbefore you reset the field you read it from.
