/*
*Write a Java program/class which creates an array with 100 random letters *using characters from ‘A’ to ‘Z’, displays the array in a 10x10 format, and displays *counts of the number of each of the random letters created.
*/
package countlettersinarray;
public class CountLettersInArray {
public static void main(String[] args) {
char[] chars = createArray();
//Display Array
System.out.println("The lowercase are: ");
displayArray(chars);
//count the occurrences of each letter
int[] counts = countLetters(chars);
//Display counts
System.out.println();
System.out.println("The occurrences of each letter are: ");
displayCounts(counts);
}
/**
* Create and array of
*/
public static char[] createArray() {
//Declare an array of characters and creaate it
char[] chars = new char[100];
//Create lowercase letters randomly and assign them to the array
for (int i = 0; i < chars.length; i++) {
chars[i] = RandomCharacter.getRandomLowerCaseLetter();
}
//Return the array
return chars;
}
/**
* Display the array of characters
*
* @param 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.println(chars[i] + " ");
}
}
}
/**
* Count the occurrences of each letter
*/
public static int[] countLetters(char[] chars) {
//Declare and create and array of 26 int
int[] counts = new int[26];
//For each lowercase letter in the array, count it
for (int i = 0; i < chars.length; i++) {
counts[chars[i] - 'a']++;
}
return counts;
}
/**
* Display counts
*/
public static void displayCounts(int[] counts) {
for (int i = 0; i < counts.length; i++) {
if ((i + 1) % 10 == 0) {
System.out.println(counts[i] + " " + (char) (i + 'a'));
} else {
System.out.print(counts[i] + " " + (char) (i + 'a') + " ");
}
}
}
}
}
}