Java基础知识Map练习作业—02
2.分析以下需求,并用代码实现:
(1)利用键盘录入,输入一个字符串
(2)统计该字符串中各个字符的数量
(3)如:
用户输入字符串"Ifyou-wanttochange-your_fate_I_thinkyoumustcome-to-the-ujiuye-to-learn-java"
程序输出结果:-(8)I(2)_(3)a(7)c(2)d(1)…
/*2.分析以下需求,并用代码实现:
(1)利用键盘录入,输入一个字符串
(2)统计该字符串中各个字符的数量
(3)如:
用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-ujiuye-to-learn-java"
程序输出结果:-(8)I(2)_(3)a(7)c(2)d(1).....*/
package day16;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class HomeWork_02 {
public static void main(String[] args) {
String str = "If~you-want~to~change-your_fate_I_think~you~must~come-to-the-ujiuye-to-learn-java";
char[] chs = str.toCharArray();
List<Character> list =new ArrayList<Character>();
Set<Character> set =new TreeSet<Character>();
for(char ch : chs) {
set.add(ch);
list.add(ch);
}
Iterator<Character> it =set.iterator();
while(it.hasNext()) {
Character character = it.next();
int cut = Collections.frequency(list, character);
StringBuilder sb = new StringBuilder();
sb.append(character+"("+cut+")");
System.out.print(sb);
}
}
}