Vending Machine Simulator: C# Implementation
Here’s a C# program implementing the Vending Machine problem:
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:
- VendingMachine Class: Defines the core logic for the vending machine.
- Can Inventory and Price: Private variables store the initial can inventory and price of a can.
- 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.
- Returns
- GiveChange Method: Calculates and displays change if the inserted money is greater than the can price.
- 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
andGiveChange
methods as needed.
- 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.