项目行中未分配的金额

时间:2015-05-15 05:04:04

标签: java

我有一个关于如何将给定金额分配给项目行的问题。 基本我有这种简单的代码。如何协调每个订单项,以便在付款金额足够时余额金额为零。如果没有,最后一项将有余额支付。对此有何建议或好的算法? 谢谢。输出在评论中。

public static void main(String[] args) {
    BigDecimal paidAmount = BigDecimal.valueOf(200);
    List<Item> items = initializeItems();
    calculateItemBalanceAmount(paidAmount, items);
    displayItems(items);
}

private static void calculateItemBalanceAmount(BigDecimal paidAmount, List<Item> items) {
    for (Item item : items) {
        if (paidAmount.compareTo(item.getTotalOwed()) > 0) {
            item.setTotalPaid(item.getTotalOwed());
            item.setBalance(item.getTotalOwed().subtract(item.getTotalPaid()));
        } else {
            item.setTotalPaid(paidAmount);
            item.setBalance(paidAmount.subtract(item.getTotalOwed()));
            break;   // Ugly
        }
    }
}

protected static List<Item> initializeItems() {
    List<Item> items = new ArrayList<>();
    Item item = new Item(BigDecimal.valueOf(1000));
    items.add(item);
    item = new Item(BigDecimal.valueOf(1000));
    items.add(item);
    item = new Item(BigDecimal.valueOf(1000));
    items.add(item);
    return items;
}

protected static void displayItems(List<Item> items) {
    System.out.print(StringUtils.rightPad("Total Owed", 15));
    System.out.print(StringUtils.rightPad("Paid", 15));
    System.out.print(StringUtils.rightPad("Balance to be paid", 15));
    System.out.println();
    for (Item i : items) {
        System.out.print(StringUtils.rightPad(i.getTotalOwed().toString(), 15));
        System.out.print(StringUtils.rightPad(i.getTotalPaid().toString(), 15));
        System.out.print(StringUtils.rightPad(i.getBalance().toString(), 15));
        System.out.println();
    }
}

private static class Item {
    private BigDecimal totalOwed = BigDecimal.ZERO;
    private BigDecimal totalPaid = BigDecimal.ZERO;
    private BigDecimal balance = BigDecimal.ZERO;

    public Item(BigDecimal totalOwed) {
        this.totalOwed = totalOwed;
    }

    public BigDecimal getTotalOwed() {
        return totalOwed;
    }

    public void setTotalOwed(BigDecimal totalAmount) {
        this.totalOwed = totalAmount;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getTotalPaid() {
        return totalPaid;
    }

    public void setTotalPaid(BigDecimal totalPaid) {
        this.totalPaid = totalPaid;
    }
}

1 个答案:

答案 0 :(得分:0)

如果我理解了您的问题,那么您需要用户必须支付的剩余余额。

因此,在您的代码中,您将获得余额,即用户拥有多少钱。当我运行你的代码时,我得到负余数为-200。

如果我查看Balance中的预期值,即200.所以基本上,你只是想要如果余数是负数,那么剩下的那么多是余额。

for loop之后,您可以添加以下代码。

BigDecimal balance = BigDecimal.valueOf(0);;
if (remainder.signum() == -1) {
    balance = remainder.negate();
    System.out.println("Balance : " + balance);
}