(^498) | One-Dimensional Arrays
Here groceryItemsis an array of 10 strings. How many characters appear in each string? We don’t
know yet. The array of strings has been instantiated, but the string objects themselves have
not been created. In other words,groceryItemsis an array of referencesto string objects, which
are set to nullwhen the array is instantiated. We must instantiate the string objects sepa-
rately. The following code segment reads and stores references to 10 strings into groceryItems:
inFile = new BufferedReader(new FileReader("infile.dat"));
outFile = new PrintWriter(new FileWriter("outfile.dat"));
...
int index; // Index into groceryItems
String[] groceryItems = new String[10]; // Provides places for 10 references
// Read strings from file inFile and store references
for (index = 0; index < groceryItems.length; index++)
{
groceryItems[index] = inFile.readLine();
}
The readLinemethod is a value-returning method that instan-
tiates the string, stores values into it, and returns a reference
to it. That is, the reference to the string is returned and stored
into groceryItems. Figure 10.9 shows what the array looks like
with values in it.
An array name with no brackets is an array variable. An ar-
ray name with brackets is a component. We can manipulate
the component just like any other variable of that type or class.
Expression Class/Type
groceryItems Reference to an array
groceryItems[0] Reference to a string
groceryItems[0].charAt(0) A character
How would you read in grocery items if you know that there
are no more than 10, but you don’t know exactly how many?
You would need a whileloop that reads in a grocery item and stores it into the first place. If
there were another item, it would be stored into the second place, and so on. As a conse-
quence, you must keep a counter of how many items you read in. The following code frag-
ment reads and stores grocery items until 10 have been read or the file is empty:
// Read and store strings from file inFile
int index = 0;
String anItem = inFile.readLine();
while(index < groceryItems.length && anItem != null)
groceryItems[ 0 ]
groceryItems[ 1 ]
groceryItems[ 2 ]
groceryItems[ 3 ]
groceryItems[ 9 ]
groceryItems
"cat food"
"butter"
"rice"
"chicken"
"bib lettuce"
Figure 10.9 groceryItemsArray
やまだぃちぅ
(やまだぃちぅ)
#1