Java Reference
In-Depth Information
The index number assigned to an element in an array always is an integer
data type, but it does not have to be a literal; it can be any expression that
evaluates to an integer. For example, if the array has been declared properly,
the following code is valid.
int index = 8;
myArray[ index ] = 71;
In the above example, the ninth element of myArray will be set to the value 71.
Using an expression for an array index number is a very powerful tool. As you
will see later in this chapter, using expressions within a loop provides an efficient
way to manipulate data in an array. Many times a problem is solved by organiz-
ing the data into arrays and then processing the data in a logical way using a
variable as an index number.
Two-Dimensional Arrays
Sometimes programmers need to create a table of values. In those cases,
a two-dimensional array, with two index numbers representing the row and
column, is appropriate. For example, the code
int[][] myTable = new int[4][3]; \\ constructs the two dimensional array (4 rows, 3 columns)
myTable[1][3] = 487; \\ assigns the value 487 to row 1, column 3
creates a two-dimensional array with 4 rows and 3 columns, and then assigns the
value 487 to row 1 and column 3 of the array. Theoretically, an array can have
many dimensions; however, it is difficult to manipulate an array that is more
than two- or three-dimensional.
Declaring Variables in the Rooms Class
Figure 5-9 displays code to declare three variables in the Rooms class: two
ints and a boolean array. The two integers will represent the number of smoking
and nonsmoking rooms — values kept current for the Rooms object. The
boolean array named occupied will hold a list of true and false values to repre-
sent the state of each room, using a true value to represent an occupied room
and a false value to represent an unoccupied room.
14
//declare class variables
15
int numSmoking;
16
int numNonSmoking;
17
boolean occupied [] ;
18
FIGURE 5-9
Search WWH ::




Custom Search