This week's book giveaway is in the Servlets forum. We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line! See this thread for details.

I am taking a Java Class. So far the assignments have been pretty simple and straight forward, smaller programs. Now they want us to create a program to calculate simple change. I am not quite sure where to even start with this one.

Here is the assignment:

You are to create a simple change program. The user enters the amount due and the amount tendered. You are to calculate how much change they should receive. You are then to break down the change in $1 bills, quarters, dimes, nickels, and pennies such that the user will receive the least amount of coins. For example, $0.80 is 3 quarters and a nickel not 8 dimes or 80 pennies.

Ok so based on this it looks like I will need some sort of basic math in there, but I am not sure where to even start on the denominations. Any guidance on where to search or what kind of thought processes I need would be much appreciated.

Tiffany,
Think about how you would do it in real life. If I pay for a $3.88 purchase with $5 what do you give me back? Why? What denomination do you think about first?

I understand how to do the basic math functions, but how do I get the information in there? We have covered how to do something basic from the command prompt, but nothing where it asks then you give an answer and you use it.

Fortuanately, making change with American dominations can use what's called a greedy algorithm. That is, look at how much change you have to make, select the biggest bill or coin less than that, subtract it from the total, and repeat.

With other denominations, the greedy approach may not lead to an optimal solution. For example, if there were no nickels, it would be better to give three dimes for 30 cents than a quarter and five pennies. That becomes a much harder problem to solve.

A basic tip would be to first convert everything into pennies. Floating point arithmetic is NOT what you want to use for money. If the user inputs $4.88, convert this to 488.

Are you supposed to prompt the user and get an input, or are they supposed to enter the values on the command prompt?

A java website that I visited suggested using BigDecimal type for money. You may find that it is a good idea to break the dollars and cents into two strings. After validating those strings, you can proceed to break them down into denominations. What happens if you use the / and % for each denomination? For instance, if the amount is greater than 50 and I say amount/50 and amount%50. Let me know if that helps.