Vending Machine Simulator: C# Implementation

Here’s a C# program implementing the Vending Machine problem:

C#
public class VendingMachine
{
    private int _canInventory = 10; // Number of cans available
    private decimal _price = 1.50m; // Price of a can

    public bool CanDispense(decimal moneyInserted)
    {
        if (_canInventory <= 0)
        {
            Console.WriteLine("Sorry, sold out!");
            return false;
        }

        if (moneyInserted < _price)
        {
            Console.WriteLine($"Insufficient funds. Please insert {_price:C2} or more.");
            return false;
        }

        Console.WriteLine("Dispensing can...");
        _canInventory--; // Decrement can inventory
        return true;
    }

    public void GiveChange(decimal moneyInserted)
    {
        decimal change = moneyInserted - _price;
        if (change > 0)
        {
            Console.WriteLine($"Returning change: {change:C2}");
        }
    }

    public static void Main(string[] args)
    {
        VendingMachine machine = new VendingMachine();

        while (true)
        {
            Console.WriteLine("Enter money (or 'q' to quit):");
            string input = Console.ReadLine();

            if (input.ToLower() == "q")
            {
                break;
            }

            decimal money;
            if (decimal.TryParse(input, out money))
            {
                if (machine.CanDispense(money))
                {
                    machine.GiveChange(money);
                }
            }
            else
            {
                Console.WriteLine("Invalid input. Please enter a number or 'q' to quit.");
            }
        }

        Console.WriteLine("Goodbye!");
    }
}

Explanation:

  1. VendingMachine Class: Defines the core logic for the vending machine.
  2. Can Inventory and Price: Private variables store the initial can inventory and price of a can.
  3. CanDispense Method: Checks if a can can be dispensed based on available inventory and inserted money.
    • Returns false if sold out or insufficient funds.
    • Prints a message if successful and decrements can inventory.
  4. GiveChange Method: Calculates and displays change if the inserted money is greater than the can price.
  5. Main Method: Creates a VendingMachine instance and runs a loop for user interaction.
    • User can enter money or ‘q’ to quit.
    • Validates user input and calls CanDispense and GiveChange methods as needed.
  6. Error Handling: Handles invalid user input and displays appropriate messages.

This program demonstrates logical operations, user input handling, and basic object-oriented programming concepts. You can further enhance it by adding features like displaying remaining cans, accepting different coin denominations, etc.

Spread the love

Similar Posts