Dan Dan - 5 months ago 23
Android Question

Android Java - withdraw money output?

In my Java Program I have a method:

private void giveCash(int money) {
int banknotes[] = {10, 20, 50, 100, 200, 500};
StringBuffer cash = new StringBuffer();
int i = banknotes.length - 1;
while (i >= 0)
if (banknotes[i] > money)
i--;
else {
cash.append(banknotes[i]).append(" ");
money -= banknotes[i];
}
// display cash in cash field
TextView cash = (TextView) findViewById(R.id.cash);
cash.setText(cash);
}


For, example, if
money == 990
the output will be: 500 200 200 50 20 20

I want to work out how to calculate how the cash will be dispensed using the following notes: 500, 200, 100, 50, 20, 10.

Answer

If I got your question correct, this is the line you want:

int amount = (int) Math.floor(money/banknotes[i]);

The whole function:

private void giveCash(int money) {
    int banknotes[] = {10, 20, 50, 100, 200, 500};
    StringBuffer cash = new StringBuffer();
    int i = banknotes.length - 1;
    while (i >= 0) {
        if (banknotes[i] > money) {
            i--;
        } else {
            int amount = (int) Math.floor(money/banknotes[i]);
            cash.append(banknotes[i]).append("x").append(amount).append(" ");
            money -= banknotes[i]*amount;
        }
    }
    TextView tvCash = (TextView) findViewById(R.id.cash);
    tvCash.setText(cash);
}

Output:

500x1 200x2 50x1 20x2