ptg7068951
110 HOUR 9:Storing Information with Arrays
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.lengthis 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 chararray 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 sec-
tion. The SpaceRemoverprogram 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: classSpaceRemover {
2: public static voidmain(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: charcurrent = 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.
The SpaceRemoverapplication stores the text “Rudolph the Red-Nosed
Reindeer” in two places—a string called mostFamousand a chararray
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 ele-
ment 1, and so on, up to “r” in element 29.