Java第11次作业--字符串处理

一、题目1

编写一个应用程序,统计输入的一个字符串中相同字符的个数,并将统计结果输出。

二、源代码

/**使用HashMap类实现Map接口,用Map集合里的方法来进行操作*/
package com;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入字符串:");
        String str=sc.nextLine();
        //声明HashMap对象
        HashMap<Character, Integer> hashMap=new HashMap<Character, Integer>();
        for (int i = 0; i < str.length(); i++) {
            char c=str.charAt(i);
            //hashMap中没有此元素,则添加至map集合中
            if(!hashMap.containsKey(c)){ //判断Map集合中是否包含'c'
                hashMap.put(c,1);
            }else {
                int count=hashMap.get(c);
                count++;//Map集合中存在此元素,则将值加1
                hashMap.put(c, count);//添加数据
            }
        }
        Set<Map.Entry<Character, Integer>> entries=hashMap.entrySet();
        for(Map.Entry<Character, Integer> entry:entries){
            System.out.println(entry.getKey()+"("+entry.getValue()+")");
        }
    }

}

三、运行结果

 

猜你喜欢

转载自www.cnblogs.com/jingxueyan/p/11891957.html