gpt4 book ai didi

java - 添加计数、小计,如果货币相同,则使用数组列表

转载 作者:行者123 更新时间:2023-12-01 12:15:17 26 4
gpt4 key购买 nike

下面是一个示例列表项目..其中包含 1* 10 =10(数量 * 货币 = 小计)如果货币相同,我想添加计数、小计。

例如

1 * 10 = 10
3 * 10 = 30

列表检查后最终的 lsit 必须是4 * 10 = 40。

public class CashModal {


private int count;
private int currency;
private int subTotal;
gettter/setter
}


listItems.add("1 * 10 = 10");
listItems.add("2 * 10 = 20");
listItems.add("1 * 5 = 5");
listItems.add("2 * 10 = 20");

cashModals=new ArrayList<CashModal>();
for(String s:listItems){
cashModal=new CashModal();
String x[]=s.split("\\*");
cashModal.setCount(Integer.parseInt(x[0].trim()));
cashModal.setCurrency(Integer.parseInt(x[1].split("\\=")[0].trim()));
cashModal.setSubTotal(Integer.parseInt(x[1].split("\\=")[1].trim()));
cashModals.add(cashModal);
subTotal=subTotal+Integer.parseInt((x[1].split("\\=")[1]).trim());
}

最佳答案

使用映射来维护数据。关键是货币字段。尝试以下代码:

ArrayList<String> listItems = new ArrayList<String>();
listItems.add("1 * 10 = 10");
listItems.add("2 * 10 = 20");
listItems.add("1 * 5 = 5");
listItems.add("2 * 10 = 20");

Map<Integer, CashModal> cashModalsMap = new HashMap<Integer, CashModal>();
int subTotal = 0;
int existingCount = 0;
int existingSubtotal = 0;
for (String s : listItems) {
String x[] = s.split("\\*");
if (!cashModalsMap
.containsKey(Integer.parseInt(x[1].split("\\=")[0].trim()))) {
CashModal cashModal = new CashModal();

cashModal.setCount(Integer.parseInt(x[0].trim()));
cashModal.setCurrency(Integer.parseInt(x[1].split("\\=")[0]
.trim()));
cashModal.setSubTotal(Integer.parseInt(x[1].split("\\=")[1]
.trim()));
cashModalsMap.put(
Integer.parseInt(x[1].split("\\=")[0].trim()),
cashModal);
subTotal = subTotal
+ Integer.parseInt((x[1].split("\\=")[1]).trim());
} else {
CashModal cashModalExisting = cashModalsMap.get(Integer
.parseInt(x[1].split("\\=")[0].trim()));
existingCount = cashModalExisting.getCount();
existingSubtotal = cashModalExisting.getSubTotal();
cashModalExisting.setCount(existingCount
+ Integer.parseInt(x[0].trim()));
cashModalExisting.setSubTotal(existingSubtotal
+ Integer.parseInt(x[1].split("\\=")[1].trim()));
cashModalsMap.put(
Integer.parseInt(x[1].split("\\=")[0].trim()),
cashModalExisting);
}
}
for(CashModal cm:cashModalsMap.values()){
System.out.println("Count:"+cm.getCount()+",Currency:"+cm.getCurrency()+",SubTotal:"+cm.getSubTotal());
}
}

关于java - 添加计数、小计,如果货币相同,则使用数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27054921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com