Build a VendingMachine type (a struct with methods) for a machine that sells one kind of item for a fixed price. 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 object is made with VendingMachine::new().
Rules:
- State. A new machine has
credit0 andprice150 (every item costs 150). Give the struct the fieldscredit: f64andprice: f64;fn new()returnsVendingMachine { credit: 0.0, price: 150.0 }. fn insert(&mut self, amount: f64)addsamountto the credit. Nothing is printed or returned.fn select(&mut self) -> Stringtries to buy one item and returns a string:- If the credit is less than the price, return
"Need N more", where N is the missing amount (price - credit) as a whole number, for example"Need 100 more". The credit does not change. - Otherwise (the credit is equal to or greater than the price, so exact payment works), subtract the price from the credit and return
"Dispensing!". Any extra money stays in the credit.
- If the credit is less than the price, return
fn refund(&mut self) -> f64returns the whole credit and sets it back to 0, so asking again right away returns 0.
You start with this driver below your code:
fn mainFunction() {
let mut m = VendingMachine::new();
m.insert(50.0);
println!("{}", m.select());
m.insert(150.0);
println!("{}", m.select());
println!("Refunded: {}", m.refund() as i32);
m.insert(150.0);
println!("{}", m.select());
println!("Refunded: {}", m.refund() as i32);
m.insert(100.0);
println!("{}", m.select());
println!("Refunded: {}", m.refund() as i32);
}
Walk through it: 50 is not enough, so you see Need 100 more. After 150 more the credit is 200, so the machine dispenses and keeps 50 (200 - 150), and the refund is 50. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100.
Expected output:
Need 100 more Dispensing! Refunded: 50 Dispensing! Refunded: 0 Need 50 more Refunded: 100
Convert the missing amount with
(self.price - self.credit) as i32 and build the text with format!("Need {} more", ...). Do the subtraction only when the item is dispensed, not when the credit is too low. If you forget it, the leftover credit is wrong and the refund is too big.
In the refund method, save the credit first, then reset it to 0, then return what you saved. Return the saved variable, not
self.credit.
struct VendingMachine {
credit: f64,
price: f64,
}
impl VendingMachine {
fn new() -> VendingMachine {
VendingMachine {
credit: 0.0,
price: 150.0,
}
}
fn insert(&mut self, amount: f64) {
self.credit += amount;
}
fn select(&mut self) -> String {
if self.credit < self.price {
return format!("Need {} more", (self.price - self.credit) as i32);
}
self.credit -= self.price;
"Dispensing!".to_string()
}
fn refund(&mut self) -> f64 {
let r = self.credit;
self.credit = 0.0;
r
}
}
Free plan: 30 tutor messages. Premium is unlimited.
