COMP2396
Loading...
Searching...
No Matches
CmdPurchase Class Reference
Inheritance diagram for CmdPurchase:
Collaboration diagram for CmdPurchase:

Public Member Functions

String execute (VendingMachine v, String[] cmdParts)
 
- Public Member Functions inherited from Command

Detailed Description

Definition at line 3 of file CmdPurchase.java.

Member Function Documentation

◆ execute()

String CmdPurchase.execute ( VendingMachine v,
String[] cmdParts )
inline

Implements Command.

Definition at line 5 of file CmdPurchase.java.

5 {
6 String productName = cmdParts[1];
7 Product product = v.getProduct(productName);
8 if (product == null) {
9 //not required for the assignment
10 return "Product not found!";
11 }
12 if (product.getQuantity() <= 0) {
13 return productName + " is out of stock!";
14 }
15 // not enough credit to buy
16 int price = product.getPrice();
17 int total = v.getTotalInsertedCoinsAmount();
18 if (total < price) {
19 //Not enough credit to buy Pepsi! Inserted $2 but needs $5
20 return "Not enough credit to buy " + productName + "! Inserted $" + total + " but needs $" + price + ".";
21 }
22 v.deductProductQuantity(product);
23 // charge the user and dump all coins remaining
24 // using $10, $5, $2, $1 in order
25 if (product.getPrice() == v.getTotalInsertedCoinsAmount()) {
26 // sample output:
27 //Dropped Pepsi. Paid $5. No change.
28 v.dumpAllCoins();
29 return "Dropped " + productName + ". Paid $" + total + ". No change.";
30 }
31 //Dropped Pepsi. Paid $16. Your change: $1, $10.
32 int change = total - price;
33 // assume infinite amount of coins from coin changer
34 ArrayList<ArrayList<Integer>> coins_list = new ArrayList<ArrayList<Integer>>();
35 for (int i = 0; i < 4; i++) {
36 coins_list.add(new ArrayList<Integer>());
37 }
38 while (change > 0) {
39 if (change >= 10) {
40 coins_list.get(3).add(10);
41 change -= 10;
42 } else if (change >= 5) {
43 coins_list.get(2).add(5);
44 change -= 5;
45 } else if (change >= 2) {
46 coins_list.get(1).add(2);
47 change -= 2;
48 } else {
49 coins_list.get(0).add(1);
50 change -= 1;
51 }
52 }
53 String return_text = "Dropped " + productName + ". Paid $" + total + ". Your change: ";
54 for (int i = 0; i < 4; i++) {
55 for (Integer c : coins_list.get(i)) {
56 return_text += "$" + c + ", ";
57 }
58 }
59 // remove the last ", " and add "."
60 return_text = return_text.substring(0, return_text.length() - 2) + ".";
61 v.dumpAllCoins();
62 return return_text;
63 }
int getQuantity()
Definition Product.java:24
int getPrice()
Definition Product.java:20
void deductProductQuantity(Product p)
Product getProduct(String name)
int getTotalInsertedCoinsAmount()

References VendingMachine.deductProductQuantity(), VendingMachine.dumpAllCoins(), Product.getPrice(), VendingMachine.getProduct(), Product.getQuantity(), and VendingMachine.getTotalInsertedCoinsAmount().

Here is the call graph for this function:

The documentation for this class was generated from the following file: