A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

题目:键盘录入一个字符串,取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq",输出格式为:a(2)b(1)k(2)...答案已被隐藏回复查看,欢迎大家将自己的想法发来一起分享一下
游客,如果您要查看本帖隐藏内容请回复




13 个回复

倒序浏览
回复 使用道具 举报 1 0

还没有学到map集合,等学到我再写一个
回复 使用道具 举报
heimalala 来自手机 中级黑马 2017-10-10 00:06:04
板凳
回复 使用道具 举报
获取一个字符串的每个字符出现的次数
回复 使用道具 举报
1.定义方法,求出指定元素在数组中出现的次数.
2.定义计数器,统计该元素的个数
3.定义方法,统计只出现一次的元素一共有多少个
4.遍历数组,拿到里面的每一个元素
5.使用上面定义的方法求出这个元素出现了几次
5.如果出现了1次,就把计数器加1
回复 使用道具 举报
package com.itheima;

import java.util.ArrayList;
import java.util.Scanner;

public class CountLetter {

        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                System.out.println("输入字符串");
                String s = sc.nextLine();
                char[] letters = s.toCharArray();
                ArrayList<Character> printedLetters = new ArrayList();
               
                for (int i = 0; i < letters.length; i++) {
                        char c = letters[i];
                        int count = 0;
                       
                        if(!printedLetters.contains(c)) {
                                for(int j = 0; j < letters.length; j++) {
                                        if(c == letters[j]) {
                                                count++;
                                        }
                                }
                                System.out.print(c + "(" + count + ")");
                                printedLetters.add(c);
                        }
                }
        }

}
回复 使用道具 举报
崇拜~
回复 使用道具 举报
还没学到
回复 使用道具 举报
看看看看看看看看看看看看看看看看看看
回复 使用道具 举报
回复 使用道具 举报

加油,一起努力
回复 使用道具 举报
济南王昭珽 发表于 2017-10-12 17:14
看看看看看看看看看看看看看看看看看看

灌水灌水灌水
回复 使用道具 举报
利用HashMap的方法:
1、利用了Map集合的键值对,键不能重复的特点

[Java] 纯文本查看 复制代码
package com.test05;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class Test {
//	键盘录入一个字符串,取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq",输出格式为:a(2)b(1)k(2)
	public static void main(String[] args) {
		String s = "abcdekka27qoq";
		//创建HashMap集合
		HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
		//将字符串转字符数组
		char[] c = s.toCharArray();
		//遍历
		for (char d : c) {
			//如果集合存在Key--d 那么就把其值加一
			if(hm.containsKey(d)){
				hm.put(d, hm.get(d) + 1);
			}else {
				//如果集合里没有,就添加进集合,并把值设置为1
				hm.put(d, 1);
			}
		}
		//利用entry遍历集合输出结果
		Set<Entry<Character,Integer>> entrySet = hm.entrySet();
		for (Entry<Character, Integer> entry : entrySet) {
			System.out.print(entry.getKey() + "(" + entry.getValue() + ")");
		}
	}

}

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马