Java随机生成字符串并统计

这个题目是呀随机产生一个字符串,并统计出现次数最多的字符(注意多个字符出现最多的情况)

 1 import java.util.*;
 2 
 3 public class CharacterCount {
 4     public static void main(String[] args) {
 5         Scanner input = new Scanner(System.in);
 6         System.out.print("Enter the length of the random string : ");
 7         int length = input.nextInt();
 8         
 9         //随机产生a~z
10         char[] array = new char[length];
11         for (int i = 0; i < length; i++) {
12             array[i] = ((char)((int)(Math.random() * 26) + 97));
13         }
14         System.out.print("随机产生的字符串为: ");
15         for (char i:array)
16             System.out.print(i);
17         System.out.println();
18         
19         //计算a~z每个字符出现的次数
20         Arrays.sort(array);
21         int[] counts = new int[26];
22         for (int j = 0; j < length; j++) {
23             counts[array[j] - 'a']++;
24         }
25         
26         //找出出现最多的次数
27         int max = counts[0];
28         for (int i = 1; i < counts.length; i++) {
29             if (max < counts[i])
30                 max = counts[i];
31         }
32         
33         //找出字符个数等于max的字母并输出
34         char[] index = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
35         System.out.print("出现次数子多的字符是 : ");
36         for (int i = 0; i < counts.length; i++) {
37             if (counts[i] == max)
38                 System.out.print(index[i]+ " ");
39         }
40         System.out.println();
41         System.out.print("出现的次数是 :" + max);
42         System.out.println();
43     }
44 }

 

 我在对其处理的时候用了一个偷懒了,没有生成字符串,而是直接使用字符数组,我们也可以随机产生一个String类型的字符串,然后转换为字符数组。

个人觉得在最后输出的时候应该有更好的方法,不需要把字母表全部列出,但是暂时还未想到。如果谁有更好的方法,希望能够留言告知。谢谢~~

转载请注明出处

 

转载于:https://www.cnblogs.com/Zubin/archive/2013/03/21/2973491.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值