【Java】统计每个字母出现的次数

package chapter6;

public class chapter6 {
	
public static void main(String[] args) {
	 char[] chars=createArray();
     System.out.println("The loeercase letters are:");
     displayArray(chars);
     int[] counts=countLetters(chars);
     System.out.println();
     System.out.println("The occurrences of each letter are:");
     displayCounts(counts);
}

//随机生成一个小写字母
public static char getRandomLowerCaseLetter() {

	return (char)('a'+Math.random()*('z'-'a'+1));
}

//随机生成100个小写字母并将其放在一个字符数组中
public static char[] createArray() {
	char[] chars=new char[100];
	for(int i=0;i <chars.length;i++) {
		chars[i] = getRandomLowerCaseLetter();
	}
	return chars;
}

//遍历随机生成的字母
public static void displayArray(char[] chars) {
	for(int i=0;i<chars.length;i++) {
		if((i+1)%20==0)
			System.out.println(chars[i]);
		else
			System.out.print(chars[i]+" ");
	}
}

//统计字母个数
public static int[] countLetters(char[] chars) {
	int counts[]=new int[26];
	for(int i=0;i<chars.length;i++) {
		counts[chars[i]-'a']++;//巧妙
	}
	return counts;
}

//打印结果
public static void displayCounts(int[] counts) {
	for(int i=0;i<26;i++)
		if((i+1)%10==0)
			System.out.println(counts[i]+" "+(char)(i+'a'));//巧妙
		else
			System.out.print(counts[i]+" "+(char)(i+'a')+" ");
}
}

猜你喜欢

转载自blog.csdn.net/qq_41547057/article/details/88360432
今日推荐