I am in Intro Algorithmic Design II need help completeing this i need comment th
ID: 3751440 • Letter: I
Question
I am in Intro Algorithmic Design II need help completeing this i need comment through program also.
INCLASS:CashRegisterDemo
Complete P12.1 (uses section 12.1) -- Class name: CashRegisterDemo (also Coin, CashRegister)
You will create the CashRegisterDemo to test the CashRegister
Question
P12.1
Modify the giveChange method of the CashRegister class in the sample code for Section 12.1 so that it returns the number of coins of a particular type to return:
int giveChange(Coin coinType)
The caller needs to invoke this method for each coin type, in decreasing value.
12.1 Sample Code For Question:
public class CashRegister
{
public static final double NICKEL_VALUE = 0.05;
public static final double DIME_VALUE = 0.1;
public static final double QUARTER_VALUE = 0.25;
. . .
public void enterPayment(int dollars, int quarters,
int dimes, int nickels, int pennies) { . . .}
. . .
}
There are really two concepts here: a cash register that holds coins and computes their total, and the values of individual coins. (For simplicity, we assume that the cash register only holds coins, not bills. Exercise P12.2 discusses a more general solution.)
It makes sense to have a separate Coin class and have coins responsible for knowing their values.
public class Coin
{
. . .
public Coin(double aValue, String aName) { . . . }
public double getValue() { . . . }
. . .
}
Then the CashRegister class can be simplified:
public class CashRegister
{
. . .
public void enterPayment(int coinCount, Coin coinType) { . . . }
. . .
}
Explanation / Answer
/** * A cash register totals up sales and computes change due. */ public class CashRegister { public static final double NICKEL_VALUE = 0.05; public static final double DIME_VALUE = 0.1; public static final double QUARTER_VALUE = 0.25; public static final double PENNY_VALUE = 0.01; private double payment; /** * Constructs a cash register with 0 balance */ public CashRegister() { payment = 0; } public void enterPayment(int coinCount, Coin coinType) { payment += coinCount * coinType.getValue(); } /** * Computes the change due and resets the machine for the next customer. * * @return the change due to the customer */ public int giveChange(Coin coinType) { double value = payment; double coinval = coinType.getValue(); int count = 0; while(value > coinval) { count++; value = value - coinval; } return count; } } class Coin { double aValue; String aName; public Coin(double aValue, String aName) { this.aValue = aValue; this.aName = aName; } public double getValue() { return aValue; } public void setValue(double aValue) { this.aValue = aValue; } public String getName() { return aName; } public void setName(String aName) { this.aName = aName; } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.