java - Unallocated amount in item line -
i have question regarding how allocate given amount line of items. basic have kind of simple code. how reconcile each line item balance amount 0 if paid amount sufficient. if not, last item has balance pay. suggestion or algorithm on this? thanks. output in comment.
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) { (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 paid", 15)); system.out.println(); (item : 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; } }
if understand question want remaining balance user has pay.
so in code getting remainder how money user has in account. when run code, getting negative remainder -200.
if @ expected value in balance
i.e. 200. basically, want if remainder negative, amount remaining balance.
after for loop
can add below code.
bigdecimal balance = bigdecimal.valueof(0);; if (remainder.signum() == -1) { balance = remainder.negate(); system.out.println("balance : " + balance); }
Comments
Post a Comment