【发布时间】:2026-01-17 19:25:01
【问题描述】:
我正在为 Java 编码课程做一个学校项目,需要一些帮助
我已经导入了一个包含一些信息的 CSV 文件,该文件已被分成一个 ArrayList,并希望汇总文件中的每个不同类别。
现在我的输出是:
Item | Category | Amount | Price | Location
Carrots | Food | 12 | $2 | Walmart
Potatoes | Food | 15 | $3 | Walmart
T-Shirt | Clothes | 1 | $16 | Walmart
Toothbrush | Cleaning | 2 | $2 | Walmart
我的目标是获取每个类别的小计,例如:
Item | Category | Amount | Price | Location
Carrots | Food | 12 | $2 | Walmart
Potatoes | Food | 15 | $3 | Walmart
Subtotal for Food is: $69
T-Shirt | Clothes | 1 | $16 | Walmart
Subtotal for Clothes is: $16
Toothbrush | Cleaning | 2 | $2 | Walmart
Subtotal For Cleaning is: $4
然后最终将整个事情汇总到最后并显示如下:
Item | Category | Amount | Price | Location
Carrots | Food | 12 | $2 | Walmart
Potatoes | Food | 15 | $3 | Walmart
Subtotal for Food is: $69
T-Shirt | Clothes | 1 | $16 | Walmart
Subtotal for Clothes is: $16
Toothbrush | Cleaning | 2 | $2 | Walmart
Subtotal For Cleaning is: $4
Total is: $89
这是我现在的代码:
public static void main(String[] args) {
ArrayList<output> csvstuff = new ArrayList<output>();
String fileName = "Project2.csv";
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()) {
String data = inputStream.next();
String[] values= data.split(",");
String Item = values[0];
String Category = values[1];
String Amount = values[2];
String Price = values[3];
String Location = values[4];
String format = "%-10s |%10s |%10s |%10s |%10s\n";
System.out.printf(format, values[0], values[1], values[2], values[3], values[4]);
output _output = new output(Item,Category,Amount,Price,Location);
csvstuff.add(_output);
}
inputStream.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
【问题讨论】:
标签: java list arraylist subtotal