統計字符串中各個字符的出現的次數(Map集合練習)
**
需求:
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)
提示:輸出結果是排序的(TreeMap)
**
package com.yang.day07.title03;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
/**
* @author WangYang
* @version 1.0
* @create 2020-02-08 18:54
* <p>
* 1.利用鍵盤錄入,輸入一個字符串
* 2.統計該字符串中各個字符的數量(提示:字符不用排序)
* 3.如:
* 用戶輸入字符串
* "If~you-want~to~change-your_fate_I_think~you~must~come-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)
* 提示:輸出結果是排序的(TreeMap)
*/
public class Title03 {
public static void main(String[] args) {
//1.利用鍵盤錄入,輸入一個字符串
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個字符串:");
//接收輸入的字符串
String line = scanner.nextLine();
//2.創建TreeMap 集合
TreeMap<Character, Integer> tm = new TreeMap<>();
/*
3.遍歷字符串,取出每一字符,
如果tm 集合中沒有改字符那麼把該字符添加到tm集合的key位置,value位置賦值爲1
如果tm 集合中存在改字符那麼value+1;
*/
for (int i = 0; i < line.length(); i++) {
//取出每一個字符做爲key
Character key = line.charAt(i);
//根據map集合的get(K key)方法獲取value值
Integer value = tm.get(key);
if (tm.get(key) == null) { //如果get(key)返回的value值爲null,那麼該字符還沒有被添加到集合
tm.put(key, 1);//該字符作爲key,value值爲1,添加到集合
} else { //如果get(key)反回的value值不爲null,那麼該字符已經出現在集合中
value++; //value值加1
tm.put(key,value); //修改該字符的value值
}
}
//遍歷HashMap集合,得到鍵和值,按照要求進行拼接
StringBuffer sb = new StringBuffer();
//得到所有的鍵值對對象的集合,再進行遍歷
Set<Map.Entry<Character,Integer>> entrys = tm.entrySet();
for (Map.Entry<Character, Integer> entry : entrys) {
Integer value = entry.getValue();
sb.append(entry.getKey()).append("(").append(entry.getValue()).append(")");
}
System.out.println(sb.toString());
}
}
結果如下: