HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Cash register allowing all coins

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
allowingallcoinsregistercash

Problem

I had to build a cash register that included a Coin class that allowed for all types of coins to be used. Please note that for this, no control structures can be used and no data structures such as arrays, lists, and what not. Any constructive criticism is welcome.

public class CashRegisterTest
{
    //Test the methods in CashRegister class
    //@param args not used
    public static void main(String[] args)
    {
        //European Coins
        final double EURO = 1;
        final double FIFTY_CENT = .5;
        final double TWENTY_CENT = .2;
        final double TEN_CENT = .1;
        final double FIVE_CENT = .05;
        final double ONE_CENT = .01;

        //American Coins
        final double DOLLAR = 1;
        final double QUARTER = 0.25;
        final double DIME = 0.10;
        final double NICKEL = 0.05;
        final double PENNY = 0.01;

        CashRegister register = new CashRegister();
        register.recordPurchase(10.99);
        register.recordPurchase(10.01);
        register.enterPayment(20, new Coin(EURO));
        register.enterPayment(2, new Coin(FIFTY_CENT));

        System.out.println(register.returnChange());

        CashRegister registerTwo = new CashRegister();
        registerTwo.recordPurchase(10.99);
        registerTwo.recordPurchase(10.01);
        registerTwo.enterPayment(20, new Coin(DOLLAR));
        registerTwo.enterPayment(4, new Coin(QUARTER));

        System.out.println(register.returnChange());
    }
}


```
public class CashRegister
{
private double purchase;
private double payment;

private int items;

//Construct a cash register with no money.
public CashRegister()
{
payment = 0;
purchase = 0;
items = 0;
}

//Records the purchase price of an item
//@param amount the price of the purchased item
public void recordPurchase(double amount)
{
purchase += amount;
items++;
}

//Enter payment recieved.
//@param amount th

Solution

You really shouldn't use double for currency. It's probably fine for this, but in a real world application, the accuracy problems you'd experience would be terrible to deal with. It's recommended that you use the currency class for money.

Also, just a small note. I like your brace style, but most Java folks use a different convention. Consistency within a code base is most important, but folks get kind of crazy about this kind of trivial stuff. Best to do as the Romans when in Rome.

public Coin(double value){
    this.value = value;
}

Code Snippets

public Coin(double value){
    this.value = value;
}

Context

StackExchange Code Review Q#148669, answer score: 7

Revisions (0)

No revisions yet.