Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^494) | One-Dimensional Arrays
but we prefer to use the lengthfield because it is specifically associated with the
array. In the future, we might modify the application to use a different constant
to set the size of occupants. Then BUILDING_SIZEwould no longer be the correct
value to terminate the loop, but occupants.lengthwould remain valid.


Sales Figures


Now let’s look at an example where the values stored in the array are sales figures
and the indexes are the product numbers. (The products are gourmet hamburg-
ers.) The product numbers range from 1 through 5. We can make the array contain
six components and just ignore the zeroth position, or we can set up five com-
ponents and make sure that we add (or subtract) one from the product number
to get the proper slot. Let’s use the latter strategy.

// Declare and instantiate an array with five real components
double[] gourmetBurgers = new double[5];

The data for this example consist of (hamburger number, day’s sales) pairs. The data file
contains a week’s worth of such pairs. The first value is an integer between 1 and 5 that rep-
resents one of the gourmet hamburgers. The next value is the sales amount for that ham-
burger for the day. Each value appears on a line by itself. The following code segment reads
in a (hamburger number, sales figure) pair:

inFile = new BufferedReader(new FileReader("salesIn.dat"));
outFile = new PrintWriter(new FileWriter("salesOut.dat"));
int burgerNumber;
doublesalesAmount;

...
burgerNumber = Integer.parseInt(inFile.readLine());
salesAmount = Double.parseDouble(inFile.readLine());


To add the sales amount to the value in the appropriate slot in the array, we use
burgerNumber – 1 as the index into the array gourmetBurgers:

gourmetBurgers[burgerNumber – 1] =
salesAmount + gourmetBurgers[burgerNumber – 1];

If we put our input and processing into a loop, we can process the week’s worth of sales
figures. We can then write the totals out to a file with the following loop:

for (burgerNumber = 0; burgerNumber < gourmetBurgers.length; burgerNumber++)
{
outFile.print("Gourmet Burger # "+ (burgerNumber + 1));
outFile.println(": "+ gourmetBurgers[burgerNumber]);
}

occupants[ 0 ]
occupants[ 1 ]
occupants[ 2 ]

occupants[ 349 ]


occupants

Figure 10.7 occupantsArray

Free download pdf