代码修改后
package com.edu.homework;
import java.util.TreeSet;
/**
* "bcdabcdeaababca",获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1)
*
*/
public class Demo2 {
public static void main(String[] args) {
String string = "bcdabcdeaababca";
//先创建一个可以自动排序且元素不能重复的treeset集合
TreeSet<Character> set = new TreeSet<Character>();
//将字符串转化成字符数组
char[] ch = string.toCharArray();
//遍历字符数组,同时将字符添加到集合中
for (int i = 0; i < ch.length; i++) {
set.add(ch[i]);
}
//遍历set集合,
for (Character ca : set) {
int count=0;
//遍历字符数组
for (int i = 0; i < ch.length; i++) {
//判段如果字符数组中的元素和set集合中的一样,count++
if (ca==ch[i]) {
count++;
}
}
System.out.print(ca+"("+count+")");
}
}
}