Page 413 - Introduction to Programming with Java: A Problem Solving Approach
P. 413
arrays do not use parentheses when specifying length. “Strings Yes” means that strings do use parentheses when specifying length. If you don’t like DFLAs,1 you can try a more analytical approach to remembering the parentheses rule. Arrays are special-case objects that don’t have methods; therefore, an array’s length must be a constant, not a method. And constants don’t use parentheses.
Partially Filled Arrays
In Figure 10.4, note how the SpeedDialList2 program declares the phoneList array to have 100 ele- ments. The program repeatedly prompts the user to enter a phone number or enter q to quit. Typically, the user will enter fewer than the maximum 100 phone numbers. That results in the phoneList array be- ing partially filled. If you have a partially filled array, as opposed to a completely filled array, you have to keep track of the number of filled elements in the array so you can process the filled elements differently from the unfilled elements. Note how the SpeedDialList2 program uses the filledElements variable to keep track of the number of phone numbers in the array. filledElements starts at zero and gets in- cremented each time the program stores a phone number in the array. To print the array, the program uses filledElements in the following for loop header.
for (int i=0; i<filledElements; i++)
It’s fairly common for programmers to accidentally access unfilled elements in a partially filled array. For example, suppose SpeedDialList2’s for loop looked like this:
{
Apago PDF Enhancer
System.out.println((i + 1) + ". " + phoneList[i]);
} // end for
Using phoneList.length in the for loop header works great for printing a completely filled array, but not so great for printing a partially filled array. In the SpeedDialList2 program, unfilled elements hold null (the default value for a string), so the above for loop would print null for each of the unfilled ele- ments. And that makes for confused and unhappy users.
10.5 Copying an Array
In the previous sections, we focused on array syntax details. In the next several sections, we’ll focus less on the syntax and more on the application side of things. In this section, we discuss a general-purpose problem—how to copy from one array to another.
Using Arrays to Hold a Store’s Prices
Suppose you use arrays to hold a store’s prices, one array for each month’s prices. Here’s the array for January’s prices:
double[] pricesJanuary = {1.29, 9.99, 22.50, 4.55, 7.35, 6.49};
10.5 Copying an Array 379
for (int i=0; i<phoneList.length; i++)
1 DFLA dumb four-letter acronym.