Start learning free

LESSON 67 OF 69 · PROJECTS: OBJECT-ORIENTED

Vending Machine in C#: A Class with State

Practice Read the full explanation

Build a VendingMachine class 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 new VendingMachine().

Rules:

  • State. A new machine has credit 0 and price 150 (every item costs 150). Declare private double credit = 0; and private double price = 150;; no constructor is needed.
  • public void Insert(double amount) adds amount to the credit. Nothing is printed or returned.
  • public string Select() tries 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.
  • public double Refund() returns the whole credit and sets it back to 0, so asking again right away returns 0.

You start with this driver below your code:

class Solution {
    public void MainFunction() {
        var m = new VendingMachine();
        m.Insert(50);
        Console.WriteLine(m.Select());
        m.Insert(150);
        Console.WriteLine(m.Select());
        Console.WriteLine("Refunded: " + m.Refund());
        m.Insert(150);
        Console.WriteLine(m.Select());
        Console.WriteLine("Refunded: " + m.Refund());
        m.Insert(100);
        Console.WriteLine(m.Select());
        Console.WriteLine("Refunded: " + m.Refund());
    }
}

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

Join the missing amount into the text with +: "Need " + (price - credit) + " 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 credit.

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 " + (price - credit) + " more";
        credit -= price;
        return "Dispensing!";
    }

    public double Refund() {
        double r = credit;
        credit = 0;
        return r;
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    C# · PROJECTS: OBJECT-ORIENTED

    Vending Machine in C#, explained

    Problem overview

    You build a VendingMachine class for a machine that sells one kind of item at a fixed price of 150. It remembers the money inserted so far, called the credit. Three methods work on it:

    • Insert(double amount) adds to the credit. It prints and returns nothing.
    • Select() tries to buy one item and returns a string. If the credit is less than the price, it returns "Need N more", where N is the missing amount, and the credit stays as it was. Otherwise it subtracts the price from the credit and returns "Dispensing!". Exact payment works, and extra money stays in the credit.
    • Refund() returns the whole credit and sets it back to 0.

    The driver inserts 50, so Select() says Need 100 more. It inserts 150 more, making 200, so the next Select() dispenses and 50 remains, which Refund() returns. Then 150 is an exact payment: it dispenses and the refund is 0. Finally 100 is short by 50 and the refund is 100.

    Approach: state plus actions

    A class bundles data with the actions that change it. Here the data is two private fields, credit starting at 0 and price set to 150. Every machine made with new VendingMachine() has its own credit, and no constructor is needed because the field initialisers give each new object its starting values.

    The one subtle point is when the credit changes. A failed purchase only reports what is missing and must leave the credit alone. The price is subtracted only after the check passes. If you subtract it on every call, the leftover credit is wrong and the refund is too big.

    Step by step

    1. Declare the class VendingMachine. Each object made from it keeps its own credit.
    2. Add private double credit = 0;, the money inserted so far.
    3. Add private double price = 150;, the cost of every item.
    4. Declare Insert as a public void method taking double amount.
    5. Add the amount with credit += amount;. This adds to what is already there instead of replacing it.
    6. Declare Select as a public method with no parameters, returning string.
    7. Handle too little money. If credit < price, return "Need " + (price - credit) + " more" on one line. Joining a number to a string with + turns the number into text. The parentheses make the subtraction happen first.
    8. Subtract the price from the credit. This line is reached only when the credit covered the price.
    9. Return "Dispensing!".
    10. Declare Refund as a public method returning double.
    11. Save the credit in a local double r. Once the credit is reset its old value is gone.
    12. Set credit back to 0.
    13. Return r, not credit, which is already 0.

    Following the credit

    The credit changes only in Insert and in a successful Select. For the start of the driver, it goes like this:

    Insert 50    credit 50
    Select       Need 100 more      (credit still 50)
    Insert 150   credit 200
    Select       Dispensing!        (credit now 50)
    Refund       returns 50
    

    The failed Select left the credit at 50, so the following insert made 200. That is the reason the subtraction sits below the guard.

    The solution in C#

    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 " + (price - credit) + " more";
            credit -= price;
            return "Dispensing!";
        }
    
        public double Refund() {
            double r = credit;
            credit = 0;
            return r;
        }
    }
    
    class Solution {
        public void MainFunction() {
            var m = new VendingMachine();
            m.Insert(50);
            Console.WriteLine(m.Select());
            m.Insert(150);
            Console.WriteLine(m.Select());
            Console.WriteLine("Refunded: " + m.Refund());
            m.Insert(150);
            Console.WriteLine(m.Select());
            Console.WriteLine("Refunded: " + m.Refund());
            m.Insert(100);
            Console.WriteLine(m.Select());
            Console.WriteLine("Refunded: " + m.Refund());
        }
    }
    

    The driver prints:

    Need 100 more
    Dispensing!
    Refunded: 50
    Dispensing!
    Refunded: 0
    Need 50 more
    Refunded: 100
    

    C# details

    • Field initialisers. private double credit = 0; runs for each new object before any method can be called. A double field would default to 0 anyway, but writing it makes the intent clear.
    • Numbers become text with +. In "Need " + (price - credit) + " more", the double 100 prints as 100, with no decimal point. A fractional amount keeps its fraction: with 100.5 inserted, Select() returns Need 49.5 more.
    • credit -= price; is shorthand for credit = credit - price;.
    • The return type matters. Select returns a string, so the driver can print the result directly with Console.WriteLine.

    Why a class and not loose variables

    The credit has to survive between calls: Insert runs, then later Select runs and must see the same money. A local variable inside a method disappears when the method returns, but a field lives as long as the object. Two machines created with new VendingMachine() do not share credit, because each object has its own copy of every field.

    Edge cases and common mistakes

    • Exact payment. The test is credit < price, so a credit of exactly 150 goes on to dispense. Using <= would refuse exact payment.
    • Subtracting before the check. The credit would go negative on a failed purchase, and the refund would be wrong.
    • Returning credit after resetting it. Refund would always return 0. Save first, reset, then return the saved value.
    • Refunding twice. The second Refund() in a row returns 0, because the first one emptied the credit.
    • Several purchases from one credit. After inserting 300, the first two Select() calls return Dispensing!, the third returns Need 150 more, and Refund() gives 0.

    Testing

    • Insert 100.5 and call Select(): Need 49.5 more. Then Refund() returns 100.5, since the failed purchase changed nothing.
    • Insert 300 and call Select() three times: Dispensing!, Dispensing!, Need 150 more. Refund() then returns 0.
    • A fresh machine's Refund() returns 0.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free