用户输入字符串"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)
使用map<Character,Integer>集合实现
public static void main(String[] args) {
/*
三、分析以下需求,并用代码实现
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)
*/
Scanner scanner=new Scanner(System.in);
System.out.println("请输入字符串");
String input = scanner.nextLine();
char[] chars = input.toCharArray();
//将输入的字符串转化为char类型数组
Map<Character, Integer> map = new HashMap<>();
//当前遍历的char数组索引,用于记录每一个元素
int index = 0;
//记录char数组找到每个字符出现的次数
int time = 0;
//遍历完char数组所有元素
while (index<chars.length){
//如果map中没有这个字符
if (!map.containsKey(index)){
//就遍历char数组,看此字符出现多少次
for (int i = 0; i < chars.length; i++) {
if (chars[index]==chars[i]) {
time++;
}
}
//遍历完就把此字符和出现次数添加入map集合
map.put(chars[index],time);
index++;
//添加完成后time置为0,次数清零
time=0;
}
}
//找到所有的字符集合
Set<Character> characters = map.keySet();
//遍历字符集合
for (Character character : characters) {
//通过字符找到出现的次数
Integer integer = map.get(character);
System.out.print(character+"("+integer+") ");
}
}