Using Arrays

You use arrays in a program as you would any variable, except for the element number between the square brackets next to the array’s name. You can use an array element anywhere a variable could be used. The following statements all use arrays that have already been defined in this hour’s examples:

elfSeniority[193] += 1;
niceChild[9428] = "Eli";
if (hostileAirTravelNations[currentNation] == true) {
    sendGiftByMail();
}

The first element of an array is numbered 0 instead of 1. This means that the highest number is one less than you might expect. Consider the following statement:

String[] topGifts = new String[10];

This statement creates an array of string variables numbered from 0 to 9. If you referred to topGifts[10] somewhere else in the program, you would get an error message referring to an ArrayIndexOutOfBoundsException.

Exceptions are another word for errors in Java programs. This exception is an “array index out of bounds” error, which means that a program tried to use an array element that doesn’t exist within its defined boundaries. You learn more about exceptions during Hour 18, “Handling Errors in a Program.”

If you want to check the upper limit of an array so you can avoid going beyond that limit, a variable called length is associated with each array that is created. The length variable is an integer that contains the number of elements an array holds. The following example creates an array and then reports its length:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",
    "Comet", "Cupid", "Donder", "Blitzen", "Rudolph" };
System.out.println("There are " + reindeerNames.length + " reindeer.");

In this example, the value of reindeerNames.length is 9, which means that the highest element number you can specify is 8.

You can work with text in Java as a string or an array of characters. When you’re working with strings, one useful technique is to put each character in a string into its own element of a character array. To do this, call the string’s toCharArray() method, which produces a char array with the same number of elements as the length of the string.

This hour’s first project uses both of the techniques introduced in this section. The SpaceRemover program displays a string with all space characters replaced with periods (.).

To get started, open the Java24 project in NetBeans, choose File, New File and create a new Empty Java File called SpaceRemover. Enter Listing 9.1 in the source editor and save it when you’re done.

Listing 9.1. The Full Text of SpaceRemover.java


 1: class SpaceRemover {
 2:     public static void main(String[] args) {
 3:         String mostFamous = "Rudolph the Red-Nosed Reindeer";
 4:         char[] mfl = mostFamous.toCharArray();
 5:         for (int dex = 0; dex < mfl.length; dex++) {
 6:             char current = mfl[dex];
 7:             if (current != ' ') {
 8:                 System.out.print(current);
 9:             } else {
10:                 System.out.print('.'),
11:             }
12:         }
13:         System.out.println();
14:     }
15: }


Run the program with the command Run, Run File to see the output shown in Figure 9.1.

Figure 9.1. The output of the SpaceRemover program.

Image

The SpaceRemover application stores the text “Rudolph the Red-Nosed Reindeer” in two places—a string called mostFamous and a char array called mfl. The array is created in Line 4 by calling the toCharArray() method of mostFamous, which fills an array with one element for each character in the text. The character “R” goes into element 0, “u” into element 1, and so on, up to “r” in element 29.

The for loop in Lines 5–12 looks at each character in the mfl array. If the character is not a space, it is displayed. If it is a space, a . character is displayed instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.43.161