Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^490) | One-Dimensional Arrays
value[ 0 ]
value[ 1 ]
value[ 2 ]
value[ 9 ]
value
value[ 25 ]
value[ 999 ]
value[ 0 ]. (The index is a constant.)
value[i],where i = 9. (The index is a variable.)
value[ 7 * j + 4 ], where j = 3 .The index is a more
complex expression.
Figure 10.5 An Index as a Constant, a Variable, and an Arbitrary Expression
In this statement, 5 is stored into an array component. If counteris 0, 5 is stored into the first
component of the array. If counteris 1, 5 is stored into the second place in the array, and so
forth. If we execute the statement
if (value[number+1] % 10 != 0)
then the expression number+ 1 selects an array component. The specific array component ac-
cessed is divided by 10 and checked to see whether the remainder is nonzero. If number+ 1 is
0 , we are testing the value in the first component; if number+ 1 is 1 , we are testing the second
place; and so on. Figure 10.5 shows the index expression as a constant, a variable, and a
more complex expression.


Out-of-Bounds Array Indexes


Given the declaration

float[] alpha = new float[100];

the valid range of index values is 0 through 99. Starting at 0 seems awkward, because we are
used to numbering things beginning with 1. However, you should not be surprised; the po-
sitions in a string begin with 0. What happens if we try to execute the statement

alpha[i] = 62.4;

when iis less than 0 or when iis greater than 99? A memory location outside the array
would be accessed, which causes an out-of-boundserror. Some languages—C++, for instance—

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf