Your Guided Program stepped you through an example of code that reads a list of of names from a datafile and stores the data in an array.
Bring up your code to follow along with the comments.
The square brackets indicate that the variable names is an array. It will reference a list of objects, all of which will be of class String. The object inputName will be used to read in a name. Remember the data types - names is an array of String, inputName is a String. They do not match! Each element in the array is of class String, so inputName and any element in the array will have matching data types.
We have decided that our program can handle up to 5 names, so we allocate the array to be size 5. In the rest of our code, we should not use the integer constant 5 when we mean the size of the array. What should we use?
What does the object called i represent? What does the object called numNames represent?
This code demonstrates the basic algorithm for reading from a datafile:
Notice that the if statement checks if there is room in the array by comparing numNames, which is currently 0, to names.length, which is 5. Remember that i is the index and numNames is how many names are in the array.
If we had an array of integers called numbers, what would the assignment statement look like?
numbers[i] = n;
What would happen if we used names.length here instead?
If you draw the code, you can see what happens.
One important aspect of this ReadIn code is that both the input loop and the for loop that prints the array stop at exactly the right place.
If either went through one too few iterations, some data would not be processed.
If either went one too many iterations, we'd be processing information that we aren't using (and probably end up with a NullPointerException or ArrayIndexOutOfBoundsException).
In order to test this code properly, we need to test our boundaries and any likely error conditions.
Suppose we want our code to work with up to 500 names. Once we change the code to make the array allocate 500 slots instead of 5, will this code still work?