统计每个字符出现的次数
- 随机生成100个小写字符并将其放入一个字符数组中
- 对数组中每个字母出现的次数进行计数:创建一个具有26个int值得数组counts,每个值存放每个字母出现的次数。
package com.ybs.practice;
/**
* @Description 类描述:
* @ClassName 类名称:
* @author yb.w
* @version 创建时间:2019年7月4日 下午2:14:00
*/
public class CountLettersInArray {
public static void main(String[] args) {
// Declare and create an array
char[] chars = createArray();
// Display the array
displayArray(chars);
// Count the occurrences of each letter
int[] counts = countLetters(chars);
// Display counts
System.out.println("The occurrences of each letter are:");
displayCounts(counts);
}
private static char[] createArray() {
char[] chars = new char[100];
for(int i = 0; i < chars.length; i++)
chars[i] = getRandomLowerCaseLetter();
return chars;
}
private static void displayArray(char[] chars) {
// Display the characters in the array 20 on each line
for (int i = 0; i < chars.length; i++) {
if((i+1) % 20 == 0)
System.out.println(chars[i]);
else
System.out.print(chars[i] + " ");
}
}
private static int[] countLetters(char[] chars) {
int[] counts = new int[26];
for(int i = 0; i < chars.length; i++) {
counts[chars[i] - 'a']++; // 'b' - 'a' = 1
}
return counts;
}
private static void displayCounts(int[] counts) {
for(int i = 0; i < counts.length; i++) {
if((i+1)%10 == 0)
System.out.println((char)(i + 'a') + ":" + counts[i]);
else
System.out.print((char)(i + 'a') + ":" + counts[i] + " ");
}
}
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}
}
结果