您的位置:首页 > 其它

用map集合巧妙解决实际问题。

2016-10-31 08:36 239 查看
import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

/**

 * Created by ttc on 16-10-30.

 */

public class Ea

{

    public static void main(String[] args)

    {

        System.out.println("请输入一段英文");

        Scanner scanner = new Scanner(System.in);

        String input = scanner.nextLine();

        String[] word = input.split(" ");

        Map<String, Integer> map = new HashMap<String, Integer>();

        for (String s : word)

        {  //如果map中不包含该单词,则取出该单词加入到map集合中,该单词作为key,值为1

            if (!map.containsKey(s))

            {

                map.put(s, 1);

            } else  //如果map当前含有该单词,则取出单词相对应的值(单词出现的个数),将其加1后,保存到集合

            {

                Integer count = map.get(s);

                count++;

                map.put(s, count);

            }

        }

        for (Map.Entry<String, Integer> me : map.entrySet())

        {

            String strkey = me.getKey();

            Integer intvalue = me.getValue();

            System.out.println(me.getKey() + "出现了" + me.getValue() + "次");

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: