在地图中操纵地图



我在一个文件中有一些购物项目,用"|"分隔。

Adam|grocery|veggies|100.00
John|fuel|gasoline|42.60
John|grocery|veggies|20.00

增值税为8.75%。

  1. 查找每个客户的总收入
  2. 对于每个客户,找出有多少支出属于哪一类
  3. 显示每个调查结果的增值税

输出:

Total Revenue:
Adam - $100.00
John - $62.60
Tax - 14.22
Shopping by Adam:
Grocery - $100.00
Tax - $8.75
Shopping by John:
Fuel - 44.60
Grocery - 20.00
Tax - $5.47

我阅读了下面代码的文件,然后创建了一个HashMapString作为Key(保存客户名称),value作为另一个HashMap(保存类别(类别名称作为Key,价格作为value))

package test;
import java.io.*;
import java.util.*;
public class GroceryStore {
    public static void main(String[] args) {
        try {
            File inFile = new File("/Users/customers.txt");
            Scanner scan = new Scanner(inFile);
            String lines = "";
            Map<String, HashMap<String, Double>> map = new HashMap<String, HashMap<String, Double>>();
            while (scan.hasNextLine()) {
                lines = scan.nextLine();
                String[] wordSplit = lines.split("\|");
                HashMap<String, Double> category = new HashMap<String, Double>();
                category.put(wordSplit[1], Double.parseDouble(wordSplit[3]));
                map.put(wordSplit[0], category);
            }
            System.out.println("Total revenue by customer: ");
            for (Map.Entry<String, HashMap<String, Double>> entry : map.entrySet()) {
                System.out.println(entry.getKey() + " - " + entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

但它并没有按照我的想法运作,无法继续。在while循环的最后一步中,当使用map.put时。这是用新的购买替换该人购买的先前条目。但我想追踪那个人的所有购买条目。然后我们应该能够显示总输出和分类输出。

有人能帮忙吗?你可能有不同的方法?

此代码未经测试,使用python的csv库将行存储在字典中,键作为第一列,在本例中是人名。

import csv
data = {}
with open('/Users/customers.txt', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter='|', quotechar='"')
    for row in spamreader:
        data[row[0]] = row
    print data

最新更新