Hey guys. I'm trying to write a program that calculates the change of something that was bought, and then I have to say, in dollars,quarters, dimes, nickels, and pennies, how I will give the change back to the customer. I have most of it done but I'm having some problems. Could anyone tell me what's wrong with my code?
/* * A cash register totals up sales and computes change due */ public class CashRegister { private double cost; private int amountpayed; private double change; private double dollarnext; private double quarternext; private double dimenext; private double nickelnext; /* * Constructs a cash register with no money on it */ public CashRegister() { cost = 0; amountpayed = 0; } /** * Records the sale of an item */ public void RecordPurchase(double purchasecost) { cost = purchasecost; } /** * Enters the payment received from the customer */ public void enterPayment(int dollar, int quarter, int dime, int nickel, int penny) { amountpayed = (int) ((dollar * 1.00) + (quarter * 0.25) + (dime * 0.10) + (nickel * 0.05) + (penny * 0.01)); change = amountpayed - cost; } public int giveDollars() { int dollarchange = (int) (change/1); dollarnext = (int) (change % 1); return dollarchange; } public int giveQuarters() { int quarterchange = (int) (dollarnext/0.25); quarternext = (int) (dollarnext % 0.25); return quarterchange; } public int giveDimes() { int dimechange = (int) (quarternext/0.10); dimenext = (int) (quarternext % 0.10); return dimechange; } public int giveNickels() { int nickelchange = (int) (dimenext/0.05); int pennynext = (int) (quarternext % 0.05); return nickelchange; } public int givePennies() { int pennychange = (int) (nickelnext/0.01); return pennychange; } }
public class ChangeTester { public static void main(String[] args) { CashRegister register = new CashRegister(); register.RecordPurchase(8.37); register.enterPayment(10, 0, 0, 0, 0); System.out.println("Dollars: " + register.giveDollars()); System.out.println("Quarters: " + register.giveQuarters()); System.out.println("Dimes: " + register.giveDimes()); System.out.println("Nickels: " + register.giveNickels()); System.out.println("Pennies: " + register.givePennies()); } }
Output:
The expected output should be 1 Dollar, 2 Quarters, 1 Dime, 0 Nickels, 3 Pennies. I have the dollar. How do I fix the other four?Dollars: 1
Quarters: 0
Dimes: 0
Nickels: 0
Pennies: 0