统计每个字符出现的次数

package six;

public class six_11 {
	public static void main(String[] args) {
		char[] chars=createArray();
		System.out.println("The lowercase letters are :");
		displayArray(chars);
		int[] counts=countLetters(chars);
		System.out.println();
		System.out.println("The occueeences of each letters are :");
		displayCounts(counts);
	}
	public static char[] createArray() {
		char[] chars=new char[100];
		for(int i=0;i<chars.length;i++)
			chars[i]=RandomCharacter.getRandomLowerCaseLetter();//生成100个随机小写字母,并赋值给chars数组;
		/*需要调用自己自定义的类*/
		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) {/*这个方法是统计字母出现的次数,这里用的方法是chars[i]-'a';
	意思是说用如果chars[i]是a那么计数器counts就是0,依次类推,不然就要用if-else,这样就很麻烦了;*/
		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<counts.length;i++) {
			if((i+1)%10==0)//判断i是否大于十,大于就多打一个空格;
				System.out.println(counts[i] + " " + (char)(i+'a'));
			else
				System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
		}
	}

}
public class RandomCharacter {
	public static char getRandomCharacter(char ch1,char ch2) {
		return (char)(ch1+Math.random()*(ch2-ch1+1));
	}
	public static char getRandomLowerCaseLetter() {
		return getRandomCharacter('a','z');
	}

java中random()函数的详细使用方法参考https://www.cnblogs.com/ningvsban/p/3590722.html

猜你喜欢

转载自blog.csdn.net/qq_41404557/article/details/88430921
0条评论
添加一条新回复
  
今日推荐