Advertisement
cd62131

Total amounts of each items

Jan 14th, 2014
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.41 KB | None | 0 0
  1. import java.io.Writer;
  2. import java.nio.charset.Charset;
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5. import java.nio.file.StandardOpenOption;
  6. import java.util.Formatter;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.Scanner;
  10. import java.util.TreeMap;
  11.  
  12. public class Total {
  13.   public static void main(String[] args) {
  14.     Scanner in = null;
  15.     try {
  16.       in = new Scanner(Paths.get("shukei.csv"));
  17.     }
  18.     catch (Exception e) {
  19.       e.printStackTrace();
  20.     }
  21.     in.useDelimiter("\\s*,\\s*|\n");
  22.     Map<String, Double> total = new TreeMap<String, Double>();
  23.     while (in.hasNextLine()) {
  24.       if (!in.hasNext()) break;
  25.       String key = in.next();
  26.       in.next(); // ignore date
  27.       in.next(); // ignore item
  28.       double amount = in.nextDouble();
  29.       if (!total.containsKey(key)) total.put(key, 0.);
  30.       total.put(key, total.get(key) + amount);
  31.     }
  32.     in.close();
  33.     Writer out = null;
  34.     try {
  35.       out =
  36.         Files.newBufferedWriter(Paths.get("result.csv"),
  37.           Charset.forName("UTF-8"), StandardOpenOption.WRITE,
  38.           StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
  39.     }
  40.     catch (Exception e) {
  41.       e.printStackTrace();
  42.     }
  43.     Formatter f = new Formatter(out);
  44.     for (Entry<String, Double> e: total.entrySet()) {
  45.       f.format("%s,%.1f\n", e.getKey(), e.getValue());
  46.     }
  47.     f.close();
  48.   }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement