Java。计算正确的变化

时间:2019-01-10 14:55:32

标签: java if-statement bigdecimal

我写了一个应该计算找零的代码(美金,硬币,硬币,……的数量)。只有“小笔钱”有效,而不是应有的方式,其余所有代码行均无响应。

    public BigDecimal deposit() {
    String money = io.readString("Please, deposit money");
    BigDecimal deposit = new BigDecimal(money);
    return deposit;
}

public void change(String itemId) throws VendingMachinePersistenceException {
    Change change = new Change();
    Item item = dao.getItem(itemId);\\this line works
    BigDecimal change1 = deposit().subtract(item.getPrice());\\this line works
    int changeBack = change1.intValue();

    io.print("Your change is : ");
        change = change.remainder(new BigDecimal("100"));
    if (changeBack/100 != 0) {
        change.setDollars(changeBack/100);
        changeBack = changeBack%100;
        io.print(change.getDollars() + " dollars, ");
    }

    if (changeBack/25 != 0) {
        change.setQuarters(changeBack/25);
        changeBack = changeBack%25;

        io.print(change.getQuarters() + " quarters, ");
    }
    if (changeBack/10 != 0) {
        change.setDimes(changeBack/10);
        changeBack = changeBack%10;
        io.print(change.getDimes()+ " dimes, ");
    }
    if (changeBack/5!= 0) {
        change.setNickels(changeBack/5);
        changeBack = changeBack%5;
        io.print(change.getNickels() + " nickels, ");
    }

    change.setPennies(changeBack);
    io.print(change.getPennies()+ " pennies.");
}

if语句或将BigDecimal转换为Int可能是问题。我不确定。 请帮忙!

1 个答案:

答案 0 :(得分:0)

由于您使用BigDecimal赚钱,因此change1可能持有5.21这样的值

将其转换为一个int只会使您获得5的changeBack,从而使您获得零钱。

,因此您可能希望将BigDecimal乘以100,然后再将其转换为int。