Start learning free

LESSON 665 OF 671 · PROJECTS: OBJECT-ORIENTED

Vending Machine in Java: 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() {
        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());
    }
}

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

Cast the missing amount to int so it prints as a whole number: (int)(price - credit). 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 " + (int)(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

    JAVA · PROJECTS: OBJECT-ORIENTED

    Vending Machine in Java, explained

    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 a String. 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

    1. Declare the class VendingMachine. Each machine 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 public and void, taking a double amount.
    5. Add the amount to credit with +=, so earlier money isn't replaced.
    6. Declare select as public, with no parameters, returning String.
    7. Handle too little money. If credit < price, return "Need ", the missing amount cast to int, and " more". Nothing is subtracted.
    8. Subtract the price from credit below the if.
    9. Return "Dispensing!". This line runs only when the credit covered the price.
    10. Declare refund as public, with no parameters, returning double.
    11. Save the credit in a double named r.
    12. Reset credit to 0.
    13. 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, so new VendingMachine() works with the default constructor Java supplies.
    • Building the message. "Need " + (int)(price - credit) + " more" joins a String, an int and another String with +. The cast turns the double 100.0 into the whole number 100, so the text says Need 100 more and not Need 100.0 more.
    • The cast truncates. Casting a double to int drops the fraction. With 100.5 inserted, the missing amount is 49.5 and the message is Need 49 more. The lesson's driver only uses whole amounts.
    • The parentheses matter. (int)(price - credit) casts the difference. Writing (int)price - credit would cast only price and leave a double in the message.
    • The if without braces. A single statement after the condition is its body. The following lines are not part of it, so they run only when the if didn'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 credit instead of r. After the reset, credit is 0, so the refund would always be 0.
    • Repeated select calls. With 300 inserted, the first two calls return Dispensing!, the third returns Need 150 more, and the following refund() returns 0.0.
    • Asking twice for a refund. After inserting 100.5, the first refund() returns 100.5 and a second one returns 0.0.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free