I am working on a program where you have to give change in coins. The program already gives the change amount, I'm just trying to figure out how to give the change in coins. This is what i have so far:
/** A cash register totals up sales and computes change due. */ package classes; public class CashRegister { // add two attributes (variables) purchase and payment private double purchase; private double payment; /** Constructor that constructs a cash register with no money in it. */ public CashRegister() { //initialize the purchase and payment to 0.0 double purchase = 0.0; double payment = 0.0; } /** Records the sale of an item. @param amount the price of the item */ public void recordPurchase(double amount) { //add the amount of purchase to purchase purchase = purchase + amount; } /** Enters the payment received from the customer; should be called once for each coin type. @param coinCount the number of coins @param coinType the type of the coins in the payment */ public void enterPayment(int coinCount, Coin coinType) { //calculate the payment payment = payment+ coinCount * coinType.getValue(); } /** Computes the change due and resets the machine for the next customer. @return the change due to the customer */ public double giveChange() { double change = purchase - payment; purchase = 0; payment = 0; return change; //calculate change,change is the difference between payment and purchase, return change } public double giveCoins() { double change = purchase - payment; purchase = 0; payment = 0; double dollars; double quarters; double nickels; double dimes; double pennies; if(change>=1) {dollars=change/1;} change=change-dollars; if(change>=.25) {quarters=change/.25;} change=change-(quarters*.25); if(change>=.1) {dimes=change/.10; } change=change-(dimes*.10); if(change>=.05) {nickels=change/.05; } change=change-(nickels*.05); if(change>=.01) {pennies=change/.01; } change=change-(pennies*.01); return dollars + quarters + dimes + nickels + pennies; } }
As you can see I'm trying to make it so say you have 5.55 in change due. The program will look at 5.50, it is greater than 1 so it will do 5.50/1 to get the dollar amount. Of course I need to find a way to round the 5.5 that will result to just 5. The program will then subtract 5 from 5.50 and continue to quaerters ad so forth.