-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountLettersInArray.java
More file actions
57 lines (45 loc) · 1.29 KB
/
CountLettersInArray.java
File metadata and controls
57 lines (45 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class CountLettersInArray {
public static void main(String[] args) {
char[] chars = createArray();
System.out.println("The lowercase letters are: ");
displayArray(chars);
// Count the occurences of each letter
int[] counts = countLetters(chars);
System.out.println();
System.out.println("The occurences of each letter are:");
displayCounts(counts);
System.out.println();
}
/** Create an array of characters */
public static char[] createArray() {
char[] chars = new char[100];
for (int i = 0; i < chars.length; i++) {
chars[i] = RandomCharacter.getRandomLowerCaseLetter();
}
return chars;
}
/** Display the array of characters */
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) {
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)
System.out.println(counts[i] + " " + (char)(i + 'a'));
else
System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
}
}
}