8.8 Using Arrays as Counters

In some circumstances, it is useful to use an array of integers as an ordered group of accumulators, or counters. For example, suppose we are analyzing a survey that has four possible answers, 0 through 3. We want to count how many people selected each answer. We could set up four counters and use an if/else statement to increment the appropriate counter. The pseudocode would be:

read first survey
while ( not end of surveys )
{
 if answer is 0
   increment counter0
 else if answer is 1
   increment counter1
 else if answer is 2
   increment counter2
 else if answer is 3
   increment counter3
 read next survey
}

That would work if we have only a few possible answers, but what if we had 100 or more answers? We would end up writing ...

Get Java Illuminated, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.