Last active
August 29, 2015 14:02
-
-
Save HabaCo/156a522629e00c84c9a4 to your computer and use it in GitHub Desktop.
使用 HashMap 計算
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.util.HashMap; | |
public class Shop { | |
public static void main(String[] args) throws IOException { | |
/* example data: | |
A,4 | |
B,3 | |
C,2 | |
B,2 | |
A,2 | |
B,1 | |
C,6 | |
B,8 | |
*/ | |
String fileName = "shopcar.txt"; | |
FileReader fr = new FileReader((fileName)); | |
BufferedReader br = new BufferedReader(fr); | |
// 建立 MAP<字串為Key,整數為Value> | |
HashMap<String, Integer> hm = new HashMap<String, Integer>(); | |
String s; | |
while((s=br.readLine())!=null){ | |
String[] t = s.split(","); | |
if (hm.get(t[0])==null) // 找不到key對應的東西(key沒出現過)則放入 | |
hm.put(t[0],Integer.parseInt(t[1])); // 放進去囉 | |
else{ // 如果找得到key相對應的東西(key出現過) | |
int tmp=hm.get(t[0]); // 則取出 value | |
hm.put(t[0],tmp+Integer.parseInt(t[1])); // 加總再放入 | |
} | |
// System.out.println(hm); // 確認累加的情形 | |
} | |
System.out.println("A 一共買了 " + hm.get("A") + " 個.\n" | |
+ "B 一共買了 " + hm.get("B") + " 個.\n" | |
+ "C 一共買了 " + hm.get("C") + " 個.\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment