Change Calculator
For our next project, let’s build a change calculator.
This program will perform the steps to calculate the ideal change to give for a purchase. For example, for $6.50 in change it should give you three $2 coins and one 50c coin.
Requirements:
- The user will enter a cost and amount paid, and the system will output the ideal change to the given.
- Allow the user to give change multiple times
- Ensure that the program does not crash when the user enters unexpected text for the cost or payment.
- Do not calculate change if the payment is insufficient.
Calculating the change to give
To get started, let’s add the code to read in the cost of the item, and the amount paid. We can keep this simple to start, with the basic sequence for these.
-
Create the variables you will need. Think about the values you will need to determine the amount of change to be given.
-
For this we will need the following variables:
string line;
which can store the input the user enters.int costOfItem;
to store the cost as an integer (in cents).int amountPaid;
to store the amount paid in cents.int changeValue;
to store the value of the change to be given.
-
-
While we are reading in these values from the user, let’s make sure that the program does not crash when the user enters anything other than a number.
When the user enters text other than a whole number for the cost or payment, then the program will crash (try it!). This is never a good thing, and we have to expect that users will make errors (intentionally or by mistake).
For this, let’s look at the code we have at the moment. The code that we have looks like this:
This reads in text from the user and stores it in
line
. We want this as a number, so we useConvert
’sToInt32
method and pass it the data inline
. If the data is not a number,ToInt32
raises an error that causes the program to crash.In the menu program we added a loop to ensure that the user’s data is a number. We can use that same logic here. The logic for this looks like this:
For this we are using a while loop, as we have different messages based on valid and invalid data entry. The loop will need to test if the line entered by the user is not an integer, and repeat the code when that is true.
Have a go at implementing this yourself now. Start with the cost of the item, and then update the payment as well. Test it out and try breaking this with different combinations of errors. Make sure it also works with valid integers.
-
You are now at a point where you have the change calculator reliably reading in the information it needs. Next we can calculate and output the change values.