View Full Version : Create a change-counting game

03-03-2014, 07:33 PM
How do I get the user to enter arbitrary combinations of coins that will be recognized as a dollar?

I am attempting to have a character ask the user to enter a number of pennies, nickels, dimes, and quarters. If the total value of the coins entered equals a dollar, the character congratulates the user. Otherwise, the character tells the user whether the amount entered was more or less than one dollar (see: Starting Out with Alice, 3/E Exercise 4).

I have created variables for the dollar and coins, one variable per each (e.g., dollar = 1, quarter = 0.25). There is an If/Else statement with the true/false actions.

My handiwork:

EDIT: If anyone can tell me how to crop the image on the forum, I will gladly do so!

03-04-2014, 07:55 AM
There are a couple of problems here.
The first one is that you are asking one question and expecting 4 answers. The simplest solution is to ask 4 questions. So the interaction might go something like:
rabbit say "Can you please give me exactly one dollar in change?"
rabbit ask "How many quarters do you have?"
quarters = <- User inputs a number
rabbit ask "How many dimes do you have?"
dimes = <- User inputs a number
rabbit ask "How many nickles do you have?"
nickles = <- User inputs a number
rabbit ask "How many pennies do you have?"
pennies = <- User inputs a number
Now you can add quarters * 0.25 + dimes * 0.1 ... to get the total and compare it to 1.

The second thing you need to deal with is that of variable types. At present you are asking for a string to be received from the user but you need a number or 4 numbers to be exact. The problem is that you cannot treat a string as a number, in other words you cannot add, and multiply strings. You could, using the Int() method, convert a string to a number but this is fraught with peril! In asking for a string you allow the user to type in whatever they want and if they type in something besides a number and you try to convert it your program will likely crash.
Side Note: A variation of this scenario is how most systems are broken into by hackers.
So the best way to get numbers in Alice is to use the "ask user for a number. The user can still mess up your program but it is not as easy. Some examples are:

The user can put in a negative number.
The user could put in a "real" or non-integer number.
The user might be able to put in an expression like 1.1*-3.

In general it is the programmers job to think of how the user could mess things up and try to exclude or correct them before the program goes south.

03-04-2014, 06:10 PM
Hey Mark! Thanks for the in-depth explanation of how I should fix the program. I will give those suggestions a try and report back with my findings :)

03-14-2014, 05:46 PM
Sorry for the delay, but if anyone is interested, my professor posted the results and it is more elegant than what I tried to hobble together! I have attached it to this post for posterity.