Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace VendingMachine
- {
- class Program
- {
- static void Main(string[] args)
- {
- // 1. read input
- string input = Console.ReadLine();
- double balance = 0;
- double[] validCoins = {0.1, 0.2, 0.5, 1, 2};
- // 2. while not start, sum coins
- while (input != "Start")
- {
- double coin = double.Parse(input);
- bool isValidCoin = false;
- // 2.1 only accept 0.1, 0.2, 0.5, 1, 2
- for (int i = 0; i < validCoins.Length; i++)
- {
- // 3. sum the money
- if (coin == validCoins[i])
- {
- isValidCoin = true;
- balance += coin;
- }
- }
- if(!isValidCoin)
- Console.WriteLine($"Cannot accept {coin}");
- input = Console.ReadLine();
- }
- // 4. while not end, buy products
- input = Console.ReadLine();
- double[] productsPrice = {2, 0.7, 1.5, 0.8, 1.0 };
- //Products = {Nuts, Water, Crisps, Soda, Coke}
- string[] products = { "Nuts", "Water", "Crisps", "Soda", "Coke" };
- while (input != "End")
- {
- bool isPurchased = false;
- bool isValidProduct = false;
- for (int i = 0; i < products.Length; i++)
- {
- if (input == products[i])
- {
- isValidProduct = true;
- // 4.1 balance -= productPrice
- if (balance >= productsPrice[i])
- {
- balance -= productsPrice[i];
- Console.WriteLine($"Purchased {products[i]}");
- isPurchased = true;
- }
- }
- }
- if(!isValidProduct)
- Console.WriteLine("Invalid product");
- if (!isPurchased && isValidProduct)
- Console.WriteLine("Sorry, not enough money");
- input = Console.ReadLine();
- }
- // 5. Print(Change: {money left})
- Console.WriteLine($"Change: {balance:f2}");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement