Chapter 12 - Java for Beginners Course

Putting everything together

By: Andres Perez

Now, we have everything ready for an app that creates some sample products in a catalog and tests our vending machine.

We will create 5 dummy products for testing as instances of ProductDetail and insert them into a HashSet. We then use that Set to create a product catalog.

Afterward, we create a VendingMachine object. And finally, we use the vending machine to create the CLI object and run the machine:

public class VendingMachineApp {

    public static void main(String[] args) {
        Set<ProductDetail> products = new HashSet<>();
        products.add(new ProductDetail("001", 2.50, "Potato Chips"));
        products.add(new ProductDetail("002", 3.00, "Soda"));
        products.add(new ProductDetail("003", 1.50, "Cookies"));
        products.add(new ProductDetail("004", 2.00, "Gummy Bears"));
        products.add(new ProductDetail("005", 2.50, "Apple"));

        ProductCatalog catalog = new InMemoryProductCatalog(products);

        VendingMachine machine = new VendingMachine(catalog);

        CLI cli = new CLI(machine);

        cli.runVendingMachine();
    }

}

When we run the previous code, the following output shows on the screen:

Welcome to our Vending Machine!

Current Balance: $0.0
Products available:
001 Potato Chips 2.5
002 Soda 3.0
003 Cookies 1.5
004 Gummy Bears 2.0
005 Apple 2.5

Please select an option:
1. Add Money
2. Request Change
3. Deliver Item
4. Exit

If we input the number 1 to insert our money, the program will output:

How much money will you add?

Let’s add 10:

Current Balance: $10.0
Products available:
001 Potato Chips 2.5
002 Soda 3.0
003 Cookies 1.5
004 Gummy Bears 2.0
005 Apple 2.5

Please select an option:
1. Add Money
2. Request Change
3. Deliver Item
4. Exit

Our funds have now been added to the balance. Now let’s buy a bag of Gummy Bears by selecting option number 3:

Please select a product using its code:

And then input the code 004:

Enjoy your product!

Current Balance: $8.0
Products available:
001 Potato Chips 2.5
002 Soda 3.0
003 Cookies 1.5
004 Gummy Bears 2.0
005 Apple 2.5

Please select an option:
1. Add Money
2. Request Change
3. Deliver Item
4. Exit

The cost of the Gummy Bears was correctly deducted. Now let’s request our change, by entering '2':

Your change is: $8.0

Current Balance: $0.0
Products available:
001 Potato Chips 2.5
002 Soda 3.0
003 Cookies 1.5
004 Gummy Bears 2.0
005 Apple 2.5

Please select an option:
1. Add Money
2. Request Change
3. Deliver Item
4. Exit

The change was given correctly. Finally, let’s exit the vending machine by entering 4:

Goodbye.