Section 9.3. Simple Array Examples


[Page 413 (continued)]

9.3. Simple Array Examples

The program in Figure 9.5 creates two arrays of ten elements each and displays their values on the Java console. In this example, the elements of intArr have not been given initial values, whereas the elements of realArr have been initialized. Note the use of the integer constant ARRSIZE to store the arrays' size. By using the constant in this way, we do not have to use the literal value 10 anywhere in the program, thereby making it easier to read and modify the program. If we want to change the size of the array the program handles, we can just change the value of ARRSIZE. This is an example of the maintainability principle.

Maintainability principle



[Page 414]

Figure 9.5. A program that displays two arrays. Its output is shown in Figure 9.6.

public class PrintArrays {   static final int ARRSIZE = 10;                           // The array's size   static int intArr[] = new int[ARRSIZE];                  // Create int array   static double realArr[] = { 1.1, 2.2, 3.3, 4.4,      5.5, 6.6, 7.7, 8.8, 9.9, 10.10 };                     // And a double array   public static void main(String args[]) {     System.out.println("Ints \t Reals");                    // Print a heading                           // For each int and double element     for (int k = 0; k < intArr.length; k++)        System.out.println( intArr[k] + " \t " + realArr[k]);// Print them     } // main() } // PrintArrays class 

Effective Design: Symbolic Constants

Using symbolic constants (final variables) instead of literal values makes the program easier to read and to maintain.


Note the use of the static qualifier throughout the PrintArrays class. This enables us to refer to the array and the other variables from within the main() method. If intArr were not declared static, we would get the compiler error attempt to make static use of a non-static variable. This use of static is justified mainly as a coding convenience rather than as a principle of object-oriented design. The only examples we have seen so far in which static elements were a necessary design element were the use of static elements in the Math classMath.PI and Math.sqrt()and the use of static final variables in TwoPlayerGameTwoPlayerGame.PLAYER_ONE.

It is not always feasible to initialize large arrays in an initializer statement. Consider the problem of initializing an array with the squares of the first 100 integers. Not only would setting these values in an initializer statement be tedious, it would also be error prone, since it is relatively easy to type in the wrong value for one or more of the squares.

Debugging Tip: Array Initialization

Initializer statements should be used only for relatively small arrays.


Figure 9.6. Output of the PrintArrays program.

Ints

Reals

0

1.1

0

2.2

0

3.3

0

4.4

0

5.5

0

6.6

0

7.7

0

8.8

0

9.9

0

10.1



[Page 415]

The example in Figure 9.7 creates an array of 50 integers and then fills the elements with the values 1, 4, 9, 16, and so on. It then prints the entire array.

Figure 9.7. A program with an array that stores the squares of the first 50 integers. Its output is shown in Figure 9.8.

public class Squares {   static final int ARRSIZE = 50;                    // The array's size   static int intArr[] = new int[ARRSIZE];           // Instantiate   public static void main(String args[]) {     for (int k = 0; k < intArr.length; k++)         // Initialize       intArr[k] = (k+1) * (k+1);     System.out.print("The first 50 squares are");     for (int k = 0; k < intArr.length; k++) {       // Print       if (k % 5 == 0)                               // For each 5th square         System.out.println(" ");                    // print a new line       System.out.print( intArr[k] + " ");     } // for   } // main() } // Squares class 

Figure 9.8. Output of the Squares program.

1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500 

This example illustrates some important points about the use of array variables. The array's elements are individual storage locations. In this example, intArr has 50 storage locations. Storing a value in one of these variables is done by an assignment statement:

intArr[k] = (k+1) * (k+1); 


The use of the variable k in this assignment statement allows us to vary the location that is assigned on each iteration of the for loop. Note that in this example, k occurs as the array index on the left-hand side of the expression, while k +1 occurs on the right-hand side as the value to be squared. The reason for this is that arrays are indexed starting at 0 but we want our table of squares to begin with the square of 1. So the square of some number n + 1 will always be stored in the array whose index is 1 less than the number itselfthat is, n.

Zero vs. unit indexing



[Page 416]

An array's length variable can always be used as a loop bound when iterating through all elements of the array:

for (int k = 0; k < intArr.length; k++)      intArr[k] = (k+1) * (k+1); 


However, it is important to note that the last element in the array is always at location length-1. Attempting to refer to intArr[length] would cause an IndexOutOfBounds-Exception because no such element exists.

Off-by-one error


Debugging Tip: Off-by-One Error

Because of zero indexing, the last element in an array is always length 1. Forgetting this fact can cause an off-by-one error.


Self-Study Exercise

Exercise 9.6

Declare an array of 100 doubles and write a loop to assign the first 100 square roots to its elements. Use Math.sqrt(double).




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net