Repository navigation
Expand file tree
/
Copy pathCountLettersInArray.java
More file actions
101 lines (71 loc) · 2.27 KB
/
Copy pathCountLettersInArray.java
File metadata and controls
101 lines (71 loc) · 2.27 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
public class CountLettersInArray {
/** Main method */
public static void main(String[] agrs) {
// Declare and create an array
char[] chars = createArray();
// Display the array
System.out.println("The lowecase letters are: ");
displayArray(chars);
//Count the occurrences of each letter
int[] counts = countLetters(chars);
// Display counts
System.out.println();
System.out.println("The occurences of each letter are: ");
displayCounts(counts);
}
/** Create an array of characters */
public static char[] createArray() {
// Declare an array of characters and create 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 */
public static void displayArray(char[] chars) {
// Display the characters in the aray 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] + " ");
}
}
/** Count the occurrences of each letter */
public static int[] countLetters(char[] chars) {
// Declare and create an 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') + " ");
}
}
}
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');
}
public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A','Z');
}
public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');
}
}