Chapter 4 - Java for Beginners Course

Giving Change

The last step in our first code example is for the user to be able to request change from the vending machine. This means, we need to return any remaining money in the balance.

In this case, we have no conditions to check, we’ll return as much money as we have in our balance. To cover this scenario, we’ll add the following method to our UnlimitedSupplyVendingMachine class:

public int giveChange() {
    int changeToGive = balance;
    balance = 0;
    return changeToGive;
}

Here, we are taking two steps, first taking a copy of the current balance into our changeToGive variable, and then updating the balance to 0 (to reflect the fact that change has been given out).

Note that the value we return is that of the local variable changeToGive as this is were we kept the balance the user had.

Let’s give this a try using an example application:

In the example project, run the JavaSimpleApp application.
UnlimitedSupplyVendingMachine vendingMachine = new UnlimitedSupplyVendingMachine();

System.out.println("Initial balance: " + vendingMachine.getBalance());

vendingMachine.addMoney(30);
System.out.println("Balance after first addition of money: " + vendingMachine.getBalance());

boolean itemDelivered = vendingMachine.deliverItem();
System.out.println("Item delivered?: " + itemDelivered);

int change = vendingMachine.giveChange();
System.out.println("Change to give: " + change);

System.out.println("Final balance: " + vendingMachine.getBalance());

Output:

Initial balance: 0
Balance after first addition of money: 30
Item delivered?: true
Change to give: 20
Final balance: 0

Analysing our example

Here, we are taking 3 initial steps after creating our vending machine object:

  1. we are printing our initial balance (which is 0),

  2. then we add 30 to the vending machine and then,

  3. request an item, which gets delivered.

At this point, our balance should be 20, as we know that each element has a cost of 10 and we had a balance of 30.

When we invoke the giveChange() method, the vending machine correctly returns 20 as the change that needs to be given to the user, and our final balance ends as 0.

Summary

There you have it, we’ve completed the first code example by adding three new behaviors/methods to the class we started with. At this point, our class can perform the actions described at the beginning of the exercise:

  1. Sells only one type of product with a fixed cost of 10.

  2. Will deliver an item only if there is enough balance.

  3. Customers can add money to the vending machine.

  4. Customers can request change if available.

  5. The vending machine has an unlimited supply of items to deliver (for simplicity purposes!).

  6. The maximum balance it can hold is 100.

Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations