博客
关于我
输入一串字符串看每一个字符的数量
阅读量:653 次
发布时间:2019-03-15

本文共 1052 字,大约阅读时间需要 3 分钟。

计算一个字符串每个字符出现的个数

  • 分析:

  • 1.使用Scanner获取用户输入的字符串

  • 2.创建Map集合,key是字符串中的字符,value是字符的个数

  • 3.遍历字符串,获取每一个字符

  • 4.使用获取得到的字符,去Map集合判断是否存在

  • key存在:

  • 通过字符(key),获取Value(字符个数)

  • value++;

  • put(key.value)把新的value存储到Map集合中

  • key不存在

  • Put(key,1)

  • 5.遍历Map集合,输出结果

    代码:

    public class Maptest {public static void main(String[] args) {  //输入字符串  Scanner sc=new Scanner(System.in);  System.out.println("请输入字符串");  String abc=sc.next();  //存储到Map中  HashMap
    map=new HashMap<>(); //是用for循环增加value值 for (char c:abc.toCharArray() ) { if (map.containsKey(c)) { Integer value = map.get(c); value++; map.put(c,value); } else { map.put(c,1); } } //使用Enteryset方法 Set
    > entries = map.entrySet(); for (Map.Entry
    entry:entries ) { //打印输出各个字符的数量 System.out.println("字符"+entry.getKey()+"有"+entry.getValue()+"个"); } }}

    显示效果

    请输入字符串

    sdkafgjhlakjflf34-=
    字符a有2个
    字符d有1个
    字符f有3个
    字符g有1个
    字符h有1个
    字符j有2个
    字符k有2个
    字符l有2个
    字符-有1个
    字符s有1个
    字符3有1个
    字符4有1个
    字符=有1个

转载地址:http://aljmz.baihongyu.com/

你可能感兴趣的文章
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
node+express+mysql 实现登陆注册
查看>>
Node+Express连接mysql实现增删改查
查看>>
node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
查看>>
Node-RED中Button按钮组件和TextInput文字输入组件的使用
查看>>
vue3+Ts 项目打包时报错 ‘reactive‘is declared but its value is never read.及解决方法
查看>>
Node-RED中Slider滑杆和Numeric数值输入组件的使用
查看>>
Node-RED中Switch开关和Dropdown选择组件的使用
查看>>
Node-RED中使用exec节点实现调用外部exe程序
查看>>
Node-RED中使用function函式节点实现数值计算(相加计算)
查看>>