Java Reference
In-Depth Information
public void recordPurchase(double amount)
{
double newTotal = purchase + amount;
purchase = newTotal;
}
Here is the giveChange method. Note that this method is a bit more
sophisticatedȌit computes the change due, and it also resets the cash register for
the next sale.
public double giveChange()
{
double change = payment - purchase;
purchase = 0;
payment = 0;
return change;
}
If you find that you have trouble with the implementation, you may need to rethink
your choice of instance fields. It is common for a beginner to start out with a set of
fields that cannot accurately reflect the state of an object. Don't hesitate to go back
and add or modify fields.
Once you have completed the implementation, compile your class and fix any
compiler errors.
Step 6 Test your class.
Write a short tester program and execute it. The tester program can carry out the
method calls that you found in Step 2.
public class CashRegisterTester
{
public static void main(String[] args)
{
CashRegister register = new
CashRegister();
register.recordPurchase(29.50);
register.recordPurchase(9.25);
register.enterPayment(50);
double change = register.giveChange();
System.out.println(change);
System.out.println("Expected: 11.25");
Search WWH ::




Custom Search