10.4 Examples of Declaring and Processing Arrays | 495
Figure 10.8 shows the contents of the array
gourmetBurgersafter the data shown have been
processed. Note that the data appear with several
values on each line, with commas between pairs,
to save space.
This example, where the index into the array
component is one less than the number assigned
to a type of hamburger, is a type of problem where
the index has semantic content. That is, the index
has meaning within the problem itself.
Character Counts
As a final example, let’s use an array to count the
number of times that each letter in the English al-
phabet is used in text, either uppercase or lower-
case. We declare an array of 26 integers, one for
each letter. Note that we do not need to set the
contents of the array slots to 0, because they are au-
tomatically initialized to 0 when we instantiate
the array.
int[] letterCount = new int[26];
letterCount[0]is the counter for the number of times we see 'A'or 'a',letterCount[1]is the
counter for the number of times we see 'B'or 'b', and letterCount[25]is the number of
times we see 'Z'or a 'z'. How do we convert a letter to its position in the array? We read a
character and see if it is a letter. If so, we convert it to uppercase using Character.toUpperCase.
The uppercase letter (cast to int) minus'A'(also cast to int) gives us the letter’s place in the
array. The following code fragment accomplishes this conversion:
if ((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'))
{
index = (int)Character.toUpperCase(letter) – (int)'A';
The following statement increments the counter for the character:
letterCount [index] = letterCount [index] + 1;
}
All of the pieces are tied together in the following application:
importjava.io.*;
public classCountLetters
{
gourmetBurgers[ 0 ]
gourmetBurgers[ 1 ]
gourmetBurgers[ 2 ]
gourmetBurgers[ 3 ]
gourmetBurgers[ 4 ]
gourmetBurgers
246.41
271.04
350.13
640.69
177.42
Data 1 50.25, 2 44.75, 4 100.33, 3 85.12, 5 20.76
3 75.20, 1 50.20, 4 95.12, 5 77.44, 2 44.75
5 12.23, 4 125.12, 3 55.23, 2 70.12, 1 44.75
1 55.66, 2 66.67, 3 77.78, 4 200.12, 5 44.75
2 44.75, 3 56.80, 4 120.00, 5 11.12, 1 45.55
Figure 10.8 gourmetBurgersArray