简体   繁体   中英

Dollars and cents counter

So I got an assignment to write a counter that adds a given amount of dollars and cents together. We were given a test class that is being used to test functionality.

We were given the following hints:

public int dollars () //The dollar count. 
ensure: this.dollars () >= 0

public int cents () //The cents count. 
ensure: 0 <= this.cents() && this.cents() <= 99

And:

public void add (int dollars, int cents) //Add the specified dollars and cents to this Counter. 
public void reset () //Reset this Counter to 0. 
ensure: this .dollars() == 0 && this.cents() == 0 

This is my current code:

public class Counter {

    private float count;

    public Counter() {
        count = 0;
    }

    public int dollars() {
        if (this.dollars() >= 0) {
            count = count + Float.parseFloat(this.dollars() + "." + 0);
        } return 0;
    }

    public int cents() {
        if (0 <= this.cents() && this.cents() <= 99) {
            count = count + Float.parseFloat(+0 + "." + this.cents());
        } else if (100 <= this.cents()) {
            count = count + Float.parseFloat(+1 + "." + (this.cents() - 100));
        }
        return 0;
    }

    public void add(int dollars, int cents) {
        dollars = this.dollars();
        cents = this.cents();
    }

    public void reset() {
        count = 0;  
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
}

I realize I am making mistakes here (supposedly at the float and trying to calculate the dollar and cents part of the float). But I can not pinpoint exactly where it fails.

public final class Counter {

    private int cents;

    public int dollars() {
        return cents / 100;
    }

    public int cents() {
        return cents;    // if you want to retrun all centes
        // return cents % 100;    // if you want to return cents less than dollar
    }

    public void add(int dollars, int cents) {
        this.cents = dollars * 100 + cents;
    }

    public void reset() {
        cents = 0;
    }
}

One very important rule for financial programming: NEVER USE FLOAT AS COUNTER MONEY . You definetly have problem with it soon or even very soon. See my example, actuall your counter could be implemented very easy just holding amount of cents as int (as I can see, you do not have part of cents).

PS One trick for a future

Imagine you need a floating point values and support all standard mathematical operations on them, like +,-,/,* . Eg dollar and integer amount of cents (like in your example) and you cannot (or do not want) to use floating operations. What should you do?

Just reserver two lowes digis in integer valus as fractional part. So let's take an example for price $12:

int price = 1200;    // 00 is reserverd for centes, , price is $12
price += 600;        // add $6, price is $18
price += 44;         // add $0.44, price is $18.55

int dollars = price / 100;   // retrieve total dollars - $18     
int cents = cents % 100;     // retrieve cents less than dollars - 44  
public class Counter {

    private int dollars = 0;
    private int cents = 0;

    public Counter(int dollars, int cents) {
        this.dollars = dollars;
        this.cents = cents;
    }

    Counter reset() {
        return new Counter(0, 0);
    }

    Counter add(int dollars, int cents) {
        if (dollars < 0 || cents < 0) {
            throw new IllegalArgumentException();
        }

        int dollarsToAdd = this.dollars + dollars;
        int centsToAdd = this.cents + cents;

        if (centsToAdd > 99) {
            dollarsToAdd += centsToAdd / 100;
            centsToAdd = centsToAdd % 100;
        }
        return new Counter(dollarsToAdd, centsToAdd);
    }

    public void print() {
        System.out.println(this.dollars + "." + this.cents);
    }

}

1) Using two counters instead of one. It makes calculations easy and avoids problems with floating points. (Check this out System.out.println(1.03 - .42); )

2) Validating inputs. Can't add negative amounts.

3) cents/100 will return number of full dollars. Since dividing int by int removes decimal points.

4) cents%100 will return remainder - cents left after converting to full dollars.

5) let's make it immutable. It will avoid concurrency problems.

Some helpful answers here. I also realized I did not understand the assignment correctly (thinking I would need a total amount of money instead of two separate counters for dollars and cents) and thus I made this harder than it needed to be.

My solution (which is verified to work by using the test class provided) is as follows:

public final class Counter {

    private int dollars;
    private int cents;

    public int dollars() {

        return dollars;
    }

    public int cents() {
        return cents;
    }

    public void add(int dollars, int cents) {
        if (dollars >= 0) {
            if (0 <= cents && cents <= 99) {
                this.dollars += dollars;
                this.cents += cents;
            }
            if (this.cents > 100 | cents > 100) {
                this.dollars += this.cents / 100;
                this.cents = this.cents % 100;
            }
            if (this.cents == 100 | cents == 100) {
                this.dollars++;
                this.cents = this.cents - 100;
            }

        }
    }

    public void reset() {
        dollars = 0;
        cents = 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM