Java Reference
In-Depth Information
Line 2 creates a new array
result
. Lines 4-7 copy elements from array
list
to array
result
. Line 9 returns the array. For example, the following statement returns a new array
list2
with elements
6
,
5
,
4
,
3
,
2
,
1
.
int
[] list1 = {
1
,
2
,
3
,
4
,
5
,
6
};
int
[] list2 = reverse(list1);
This section presents a program to count the occurrences of each letter in an array of
characters.
Key
Point
The program given in Listing 6.4 does the following:
1. Generates
100
lowercase letters randomly and assigns them to an array of characters, as
shown in Figure 6.8a. You can obtain a random letter by using the
getRandomLower-
CaseLetter()
method in the
RandomCharacter
class in Listing 5.10.
2. Count the occurrences of each letter in the array. To do so, create an array, say
counts
,
of
26 int
values, each of which counts the occurrences of a letter, as shown in Figure
6.8b. That is,
counts[0]
counts the number of
a
's,
counts[1]
counts the number of
b
's, and so on.
chars[0]
chars[1]
…
…
chars[98]
chars[99]
counts[0]
counts[1]
…
…
counts[24]
counts[25]
…
…
…
…
(a) (b)
F
IGURE
6.8
The
chars
array stores
100
characters, and the
counts
array stores
26
counts,
each of which counts the occurrences of a letter.
L
ISTING
6.4
CountLettersInArray.java
1
public class
CountLettersInArray {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Declare and create an array
5
char
[] chars =
createArray();
create array
6
7
// Display the array
8 System.out.println(
"The lowercase letters are:"
);
9
10
11
displayArray(chars);
pass array
// Count the occurrences of each letter
countLetters(chars)
12
int
[] counts =
;
return array
13
14
// Display counts
15 System.out.println();
16 System.out.println(
"The occurrences of each letter are:"
);
17
18 }
19
20
displayCounts(counts);
pass array
/** Create an array of characters */