Untitled
unknown
java
2 years ago
3.1 kB
23
Indexable
import java.io.*;
import java.util.*;
interface Drink {
int getPrice();
String getName();
int getQuantityLeft();
void serveDrink();
}
class ServeDrinkSummary {
Drink servedDrink;
int change;
ServeDrinkSummary(Drink servedDrink, int change) {
this.servedDrink = servedDrink;
this.change = change;
}
}
class OutOfStockException extends Exception {
public OutOfStockException(String message) {
super(message);
}
}
class InsufficientMoneyException extends Exception {
public InsufficientMoneyException() {
super("Insufficient money");
}
}
class VendingMachine {
private final Drink[] drinks = new Drink[3];
void registerDrink(int buttonIdx, Drink drink) {
drinks[buttonIdx] = drink;
}
ServeDrinkSummary dispatch(int buttonPressed, int money)
throws OutOfStockException, InsufficientMoneyException {
Drink drink = drinks[buttonPressed];
if (drink.getQuantityLeft() == 0) {
throw new OutOfStockException(drink.getName() + " is out of stock");
} else if (money < drink.getPrice()) {
throw new InsufficientMoneyException();
} else {
drink.serveDrink();
int change = money - drink.getPrice();
return new ServeDrinkSummary(drink, change);
}
}
}
class Coke implements Drink {
private int price;
private String name;
private int quantityLeft;
public Coke(int price, String name, int quantityLeft) {
this.price = price;
this.name = name;
this.quantityLeft = quantityLeft;
}
public int getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
public int getQuantityLeft() {
return this.quantityLeft;
}
public void serveDrink() {
if (this.quantityLeft > 0)
this.quantityLeft -= 1;
}
}
class Fanta implements Drink {
private int price;
private String name;
private int quantityLeft;
public Fanta(int price, String name, int quantityLeft) {
this.price = price;
this.name = name;
this.quantityLeft = quantityLeft;
}
public int getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
public int getQuantityLeft() {
return this.quantityLeft;
}
public void serveDrink() {
if (this.quantityLeft > 0)
this.quantityLeft -= 1;
}
}
class Sprite implements Drink {
private int price;
private String name;
private int quantityLeft;
public Sprite(int price, String name, int quantityLeft) {
this.price = price;
this.name = name;
this.quantityLeft = quantityLeft;
}
public int getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
public int getQuantityLeft() {
return this.quantityLeft;
}
public void serveDrink() {
if (this.quantityLeft > 0)
this.quantityLeft -= 1;
}
}Editor is loading...
Leave a Comment