Java Reference
In-Depth Information
11
// Count the occurrences of each letter
12
int
[] counts = countLetters(chars);
return array
13
14
// Display counts
15 System.out.println();
16 System.out.println(
"The occurrences of each letter are:"
);
17
displayCounts(counts);
pass array
18 }
19
20
/** Create an array of characters */
21
public static char
[] createArray() {
22
// Declare an array of characters and create it
23
char
[] chars =
new char
[
100
];
24
25
// Create lowercase letters randomly and assign
26
// them to the array
27
for
(
int
i =
0
; i < chars.length; i++)
28 chars[i] = RandomCharacter.getRandomLowerCaseLetter();
29
30
// Return the array
31
return
chars;
32 }
33
34
/** Display the array of characters */
35
public static void
displayArray(
char
[] chars) {
36
// Display the characters in the array 20 on each line
37
for
(
int
i =
0
; i < chars.length; i++) {
38
if
((i +
1
) %
20
==
0
)
39 System.out.println(chars[i]);
40
else
41 System.out.print(chars[i] +
" "
);
42 }
43 }
44
45
/** Count the occurrences of each letter */
46
public static int
[] countLetters(
char
[] chars) {
47
// Declare and create an array of 26 int
48
int
[] counts =
new int
[
26
];
49
50
// For each lowercase letter in the array, count it
51
for
(
int
i =
0
; i < chars.length; i++)
52 counts[chars[i] -
'a'
]++;
53
54
increase count
return
counts;
55 }
56
57
/** Display counts */
58
public static void
displayCounts(
int
[] counts) {
59
for
(
int
i =
0
; i < counts.length; i++) {
60
if
((i +
1
) %
10
==
0
)
61 System.out.println(counts[i] +
" "
+ (
char
)(i +
'a'
));
62
else
63 System.out.print(counts[i] +
" "
+ (
char
)(i +
'a'
) +
" "
);
64 }
65 }
66 }
Search WWH ::
Custom Search