产生随机字符并进行计数

本文介绍了一个Java程序,该程序能够生成一个包含100个随机小写字母的数组,并统计每个字母出现的频率。通过ASCII值转换,程序有效地记录了字母的出现次数,并以清晰的格式显示统计结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



package array;

//import java.util.Scanner;

public class CountLetter {

 public static void main(String[] args) {
  // 统计每个字母出现的次数
  
  char[] chars = creatArray();
  
  System.out.println("The lowersletter is ");
  displayArray(chars);
  
  int[] counts = countchars(chars);
  System.out.println();
  
  System.out.println("The occurences of each letter are ");
  displayCount(counts);
 }
 
 public static char[] creatArray()//创建一个数组
 {
  //Scanner input = new Scanner(System.in);
  char[] chars = new char[100];
  for(int i=0;i<100;i++)
   chars[i] = getRandomLowerCaseLetter(); //调用函数产生随机字符
  return chars;
  
 }

 public static void displayArray(char[] a)//打印出数组
 {
  for(int i=0;i<100;i++)
  {
   if((i+1)%20 ==0)//控制输出格式
    System.out.println(a[i]);
   else
    System.out.print(a[i]+" ");
  }
 }

 public static int[]  countchars(char[] b)//进行计数
 {
  
  int[] counts = new int[26];
  for(int i=0;i<b.length;i++)
  {
   counts[b[i]-'a']++;//巧妙运用字符的计算转换为ACSII值
  }
  return counts;//只用返回首地址即返回数组
  
 }

 public static void displayCount(int[] c)//打印出对应的数量
 {
  for(int i=0;i<c.length;i++)
  {
   if((i+1)%10==0)//控制格式
    System.out.println(c[i]+" "+(char)(i+'a'));
   else
    System.out.print(c[i]+" "+(char)(i+'a')+" ");
  }
 }

 public static char getRandomLowerCaseLetter()
 {
  return getRandomCharacter('a','z');
 }
 
 public static char getRandomCharacter(char a,char b)
 {
  return (char)(a+Math.random()*(b-a+1));//利用Math.random()产生随机数,然后进行强制转换变为字符
 }
 
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

洋葱ycy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值