这个题目是呀随机产生一个字符串,并统计出现次数最多的字符(注意多个字符出现最多的情况)
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类型的字符串,然后转换为字符数组。
个人觉得在最后输出的时候应该有更好的方法,不需要把字母表全部列出,但是暂时还未想到。如果谁有更好的方法,希望能够留言告知。谢谢~~
转载请注明出处