java统计每个字母出现的次数

package test;
 
public class project1 {
	public static void main(String []args) {
       char[] chars=createArray();
       displayArray(chars);
       int[] counts=countLetters(chars);
       System.out.println("the occurrences of each letter are:");
       displayCount(counts);
	}
    //随机生成100个小写字母
	public static char[] createArray() {
		char[] chars=new char[100];
		for(int i=0;i<chars.length;i++) 
			chars[i]=(char)(Math.random()*26+'a');
		return chars;
	}
	
	//计算每个字母出现的次数
	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;
	}
	
	//输出100个字母
	public static void displayArray(char[] chars) {
		for(int i=0;i<chars.length;i++) {
			if((i+1)%10==0) {
				System.out.println(chars[i]);
			}else
			{
				System.out.print(chars[i]+" ");
			}
		}
	}
	
	//输出每个字母出现的次数
	public static void displayCount(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]+"   ");
			}
		}
	}
}

运行结果:

s e d g z r o p i j
g w d s h l n z z f
w g j n y g z q c v
t w f z h t w a n l
a m u s i t c d e k
n k b h b p a e r f
g b d m j e q g y t
v z c b n h o k m n
k s q v d w o i w n
e o x p m h s g w j
the occurrences of each letter are:
a 3   b 4   c 3   d 5   e 5   f 3   g 7   h 5   i 3   j 4
k 4   l 2   m 4   n 7   o 4   p 3   q 3   r 2   s 5   t 4
u 1   v 3   w 7   x 1   y 2   z 6   

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值