简体   繁体   中英

Java. counting the correct change

I've written a code that supposed to count the change(number of dollars bills, dimes coins, pennies ....). only "pennies" work, but not the way it supposed to be, all the rest lines of code never responds.

    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.");
}

It could be the issue with if statements or converting BigDecimal to Int. I'm not sure. Please, help!

since you're using BigDecimal for money, change1 is probably holding a value like 5.21

converting that to an int will get you just 5 for changeBack, resulting in a nickel for change.

so you probably want to multiply the BigDecimal by 100 before converting it into an int.

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