- package test;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Scanner;
- import java.util.Set;
- import java.util.TreeMap;
- /**
- * 统计字符串相同字符的长度并打印
- * @author fjg
- *
- */
- public class Test {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in); //使用Scanner接受从键盘的输入
- System.out.println("请输入一段字符:");
- String str = input.nextLine(); //从键盘接受输入的数据
- Map<Character,Integer> tree = new TreeMap<Character,Integer>();//利用TreeMap来保存某个字符出现的次数
-
- for(int i=0;i<str.length();i++){
- char ch = str.charAt(i);
- //如果第一次出现,则初始为1
- if(!tree.containsKey(ch)){
- tree.put(ch, 1);
- }
- else{
- int auto = tree.get(ch)+1; //如果在容器中已存在,则在原来的基础上+1
- tree.put(ch, auto);
- }
- }
- // 使用Iterator,方便遍历输出
- Iterator<Character> iter = tree.keySet().iterator();
- List<Integer> list = new ArrayList<Integer>();
-
- while(iter.hasNext()){
- //获得字符对象信息
- char temp = iter.next();
-
- System.out.print(temp);
- list.add(tree.get(temp));
-
- }
- System.out.println();
- int max = Collections.max(list);
- for(int i=0;i<max;i++){
- for(int a=0;a<=list.size();a++){
- if(i<a)
- System.out.print("*");
- }
- System.out.println();
- }
-
-
- }
- }
复制代码 请输入一段字符:
aaabbc
abc
***
**
* |