NTU-OOP-Tuts-2024/T3Q1-extra1/src/VendingMachine.java

100 lines
2.8 KiB
Java

import drinks.*;
import coins.*;
import java.util.Scanner;
public class VendingMachine {
private static final Drink[] availableDrinks = new Drink[3];
private static final Coin[] acceptableCoins = new Coin[4];
private static final Scanner sc = new Scanner(System.in);
int drinkSelection = 0;
private boolean isRunning = true;
public VendingMachine()
{
availableDrinks[0] = new Beer();
availableDrinks[1] = new Coke();
availableDrinks[2] = new GreenTea();
acceptableCoins[0] = new Ten();
acceptableCoins[1] = new Twenty();
acceptableCoins[2] = new Fifty();
acceptableCoins[3] = new Dollar();
}
public void start()
{
while (isRunning)
{
collectOrder();
checkChange(collectCoins());
printReceipt();
}
}
public void stop()
{
isRunning = false;
}
private void collectOrder()
{
System.out.print("====== Vending Machine ====== \n");
int i = 1;
for (Drink drink : availableDrinks)
System.out.printf("|%d. Buy %s ($%.2f) \n", i++, drink.getName(), drink.getPrice());
System.out.print("|============================ \n");
do {
System.out.println("Please enter selection: ");
drinkSelection = sc.nextInt() - 1;
} while (drinkSelection < 0 || drinkSelection > availableDrinks.length);
}
private double collectCoins()
{
double amount = 0.0;
presentCoinMenu();
do {
amount += processCoinAmount();
System.out.printf("Coins inserted: %.2f \n", amount);
} while (amount < availableDrinks[drinkSelection].getPrice());
return amount;
}
private void checkChange(double amount)
{
if (amount > availableDrinks[drinkSelection].getPrice())
System.out.printf("Change $ %.2f \n", amount - availableDrinks[drinkSelection].getPrice());
}
private void printReceipt()
{
System.out.println("Please collect your drink");
System.out.println("Thank you!!");
}
private void presentCoinMenu()
{
System.out.println("Please insert coins: ");
System.out.println("========== Coins Input ===========");
for (Coin coin : acceptableCoins)
System.out.printf("|Enter '%c' for %s input \n", coin.getSymbol(), coin.getDescription());
System.out.println("==================================");
}
private double processCoinAmount()
{
char insertedCoin = sc.next().charAt(0);
insertedCoin = Character.toUpperCase(insertedCoin);
for (Coin coin : acceptableCoins)
if (insertedCoin == coin.getSymbol())
return coin.getValue();
return 0.0;
}
}