Java Reference
In-Depth Information
14 uses the random value to determine which frequency element to increment during
each iteration of the loop. The calculation in line 14 produces random numbers from 1 to
6, so the array frequency must be large enough to store six counters. However, we use a
seven-element array in which we ignore frequency[0] —it's more logical to have the face
value 1 increment frequency[1] than frequency[0] . Thus, each face value is used as an
index for array frequency . In line 14, the calculation inside the square brackets evaluates
first to determine which element of the array to increment, then the ++ operator adds one
to that element. We also replaced lines 49-51 from Fig. 6.7 by looping through array fre-
quency to output the results (lines 19-20). When we study Java SE 8's new functional pro-
gramming capabilities in Chapter 17, we'll show how to replace lines 13-14 and 19-20
with a single statement!
7.4.7 Using Arrays to Analyze Survey Results
Our next example uses arrays to summarize data collected in a survey. Consider the fol-
lowing problem statement:
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the
student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses
in an integer array and determine the frequency of each rating.
This is a typical array-processing application (Fig. 7.8). We wish to summarize the num-
ber of responses of each type (that is, 1-5). Array responses (lines 9-10) is a 20-element
integer array containing the students' survey responses. The last value in the array is inten-
tionally an incorrect response ( 14 ). When a Java program executes, array element indices
are checked for validity—all indices must be greater than or equal to 0 and less than the
length of the array. Any attempt to access an element outside that range of indices results
in a runtime error that's known as an ArrayIndexOutOfBoundsException . At the end of
this section, we'll discuss the invalid response value, demonstrate array bounds checking
and introduce Java's exception-handling mechanism, which can be used to detect and
handle an ArrayIndexOutOfBoundsException .
1
// Fig. 7.8: StudentPoll.java
2
// Poll analysis program.
3
4
public class StudentPoll
5
{
6
public static void main(String[] args)
7
{
8
// student response array (more typically, input at runtime)
9
int [] responses = { 1 , 2 , 5 , 4 , 3 , 5 , 2 , 1 , 3 , 3 , 1 , 4 , 3 , 3 , 3 ,
10
2 , 3 , 3 , 2 , 14 };
11
int [] frequency = new int [ 6 ]; // array of frequency counters
12
13
// for each answer, select responses element and use that value
// as frequency index to determine element to increment
for ( int answer = 0 ; answer < responses.length; answer++)
{
14
15
16
Fig. 7.8 | Poll analysis program. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search