Programming and Problem Solving with Java

(やまだぃちぅ) #1
12.3 Multidimensional Arrays | 591

12.3 Multidimensional Arrays


Java does not place a limit on the number of dimensions that an array can have.
We can generalize our definition of an arrayto cover all cases.
You might have guessed that you can have as many dimensions as you want.
How many should you use in a particular case? As many as there are features that
describe the components in the array.
Take, for example, a chain of department stores. Monthly sales figures must
be kept for each item by store. There are three important pieces of information
about each item: the month in which it was sold, the store from which it was
purchased, and the item number. We can declare an array to summarize this data
as follows:


int[][][] sales; // Declare array of sales figures
// First dimension represents number of stores;
// second dimension represents months;
// third dimension represents items
sales = new int[100][12][10]; // Instantiate array


Figure 12.6 provides a graphic representation of the salesarray.
The number of components in salesis 12,000 (10  12 100). If sales fig-
ures are available only for January through June, then half of the array is empty.
If we want to process the data in the array, we must use subarray processing.
The following code fragment sums and prints the total number of each item sold
this year to date by all stores:


int currentMonth = 6; // Range: 1..12


for (int item = 0; item < sales[0][0].length; item++)
{
numberSold = 0;
for (int store = 0; store < sales.length; store++)
for (int month = 0; month < currentMonth; month++)
numberSold = numberSold + sales[store][month][item];
outFile.println("Item # "+ item + " Sales to date = "



  • numberSold);
    }


Because itemcontrols the outer forloop, we are summing each item’s sales by monthand
store. If we want to find the total sales for each store, we use storeto control the outer for
loop, summing that location’s sales by monthand itemwith the inner loops.


int currentMonth = 6;


for (int store = 0; store < sales.length; store++)


Array A collection of compo-
nents, all of the same type,
ordered on Ndimensions (N>=
1). Each component is accessed
by Nindexes, each of which rep-
resents the component’s posi-
tion within that dimension.

items

stores

months

Figure 12.6 salesArray
Free download pdf