Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^592) | Multidimensional Arrays and Numeric Computation


{

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

It takes two loops to access each component in a two-dimensional array; it takes three
loops to access each component in a three-dimensional array. The task to be accomplished
determines which index controls the outer loop, the middle loop, and the inner loop. If we
want to calculate monthly sales by store,monthcontrols the outer loop and storecontrols the
middle loop. If we want to calculate monthly sales by item,monthcontrols the outer loop
and itemcontrols the middle loop.
A multidimensional array can be a parameter and can serve as the return type of a
method. Just be sure that you have as many pairs of brackets as you have dimensions fol-
lowing the type or class name.

12.4 Vector Class


We cannot end our discussion of arrays without mentioning a class that is available in the
java.utilpackage: the Vectorclass. The Vectorclass offers functionality similar to that of the
one-dimensional array. In fact, the array is the underlying implementation structure used
in this class. In contrast to an array, however, a vector can grow and shrink; its size is not fixed
for its lifetime. The Vectorclass provides methods to manipulate items at specified index po-
sitions. In many ways, the vector resembles the general-purpose list classes that we de-
signed in Chapter 11. We explore the Vectorclass in more detail in the exercises.

12.5 Floating-Point Numbers


We have used floating-point numbers off and on since we introduced them in Chapter 2, but
we have not examined them in depth. Floating-point numbers have special properties when
used on the computer. Thus far, we’ve tended to ignore these properties, but now it’s time
to consider them in detail.

Representation of Floating-Point Numbers


As we know, Java represents numbers in the binary number system and its different nu-
meric types use different numbers of bits. To simplify the following discussion, let’s assume
that we have a computer in which each memory location is the same size and is divided into
a sign plus five decimal digits. When we define a variable or constant, the location assigned
to it consists of five digits and a sign. When we define an integral variable or constant, the
interpretation of the number stored in that place is straightforward. When we define a float-
Free download pdf