Search⌘ K

Partially Filled Arrays

Explore how to manage partially filled arrays in Java, including setting array capacity, using sentinel values to stop input, and storing only valid data. Understand the difference between array capacity and contents, and learn to ensure arrays hold meaningful values during program execution.

Example: Count the items in a data set

Earlier, we asked the user for the size of the input data set when we calculated the average and computed deviations. Suppose that our program, not the user, counts the items in the data set. For example, let’s read up to 50 positive integers, counting them and saving them in an array. As soon as we read an integer that is not positive, we will stop. Recall that the signal to stop—in this case, a zero or negative number—is called a sentinel.

Although we do not know exactly how many integers we will read, we can choose an upper limit on ...