统计一段文字中每个字符出现的次数,并输出结果(包含字符及其出现次数)保存在一个适合的集合中。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/New_feature/article/details/78340875
import java.util.*;

public class Test {
    public static void main(String []args){
        String text;                              //存一段文本
        Set keys;                                 //存键值
        Map<Character,Integer> map = new HashMap<Character, Integer>();

        Scanner scn = new Scanner(System.in);
        System.out.println("请输入一段文本");
        text = scn.nextLine();                     //存入一行文本

        System.out.println(text);
        for(int i = 0; i < text.length(); i++){
            if(map.containsKey(text.charAt(i))){    //如果该键已存在,则把值加1
                map.put(text.charAt(i),map.get(text.charAt(i))+1);
            }else{
                map.put(text.charAt(i),1);          //否则,不存在,就把该字符作为键存入map,其值为1
            }
        }
        keys = map.keySet();
        Iterator it = keys.iterator();
        while(it.hasNext()){
            Character x = (Character)it.next();       //把这个键存下来
            System.out.println(x+":"+map.get(x));     //输出字符和个数
        }
    }
}

猜你喜欢

转载自blog.csdn.net/New_feature/article/details/78340875
今日推荐