Java Reference
In-Depth Information
7.15
Suppose the following code is written to reverse the contents in an array, explain
why it is wrong. How do you fix it?
Check
Point
int [] list = { 1 , 2 , 3 , 5 , 4 };
for ( int i = 0 , j = list.length - 1 ; i < list.length; i++, j--) {
// Swap list[i] with list[j]
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
7.8 Case Study: Counting the Occurrences
of Each Letter
This section presents a program to count the occurrences of each letter in an array of
characters.
Key
Point
The program given in Listing 7.4 does the following:
1. Generates 100 lowercase letters randomly and assigns them to an array of characters, as
shown in Figure 7.7a. You can obtain a random letter by using the getRandomLower-
CaseLetter() method in the RandomCharacter class in Listing 6.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  7.7b. 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 7.7
The chars array stores 100 characters, and the counts array stores 26 counts,
each of which counts the occurrences of a letter.
L ISTING 7.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
displayArray(chars);
pass array
10
 
 
 
Search WWH ::




Custom Search