用HashMap統計輸入字串中各個“字元”的數量
阿新 • • 發佈:2021-02-07
技術標籤:java
1.利用鍵盤錄入,輸入一個字串
2.統計該字串中各個字元的數量(提示:字元不用排序)
3.如:
使用者輸入字串"Ifyou-wanttochange-your_fate_I_thinkyoumustcome-to-the-dark-horse-to-learn-java"
程式輸出結果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
**==================================================================**
public class Test {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//建立HashMap
Map<Character,Integer> map=new HashMap<>();
System.out.println("輸入:");
String str=input.next();
//將字串拆分成字元,放入字元陣列
char [] arr=str.toCharArray();
System.out.println(arr);
for (char c : arr){
int count=0;
if (map.containsKey(c)){
Integer value = map.get(c);
map.put(c,++value);
}else {
map.put(c, ++count);
}
}
System.out.println(map);
}
}
測試: