天天看點

【2019.07.04】java 統計每個字元出現的次數統計每個字元出現的次數結果

統計每個字元出現的次數

  1. 随機生成100個小寫字元并将其放入一個字元數組中
  2. 對數組中每個字母出現的次數進行計數:建立一個具有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');
	}
}

           

結果

【2019.07.04】java 統計每個字元出現的次數統計每個字元出現的次數結果