Java Reference
In-Depth Information
Self-Test Exercises
(continued)
14. Rewrite the class
GolfScores
from Display 6.4 using the method
differenceArray
from Exercise 13.
15. Rewrite the class
GolfScores
from Display 6.4 making the array of scores a
static variable. Also, make the
int
variable
numberUsed
a static variable. Start
with Display 6.4, not with the answer to Exercise 14.
Hint:
All, or at least most,
methods will have no parameters.
EXAMPLE:
A Class for Partially Filled Arrays
If you are going to use some array in a disciplined way, such as using the array as a par-
tially filled array, then it is often best to create a class that has the array as an instance vari-
able and to have the constructors and methods of the class provide the needed operations
as methods. For example, in Display 6.5 we have written a class for a partially filled array
of doubles. In Display 6.6 we have rewritten the program in Display 6.4 using this class.
In Display 6.6 we have written the code to be exactly analogous to that of Display
6.4 so that you could see how one program mirrors the other. However, this resulted
in occasionally recomputing a value several times. For example, the method
computeAverage
contains the following expression three times:
a.getNumberOfElements()
Since the
PartiallyFilledArray
a
is not changed in this method, these each return
the same value. Some programmers advocate computing this value only once and sav-
ing the value in a variable. These programmers would use something like the following
for the definition of
computeAverage
rather than what we used in Display 6.6. The
variable
numberOfElementsIna
is used to save a value so it need not be recomputed.
public static double
computeAverage(PartiallyFilledArray a)
{
double
total = 0;
double
numberOfElementsIna = a.getNumberOfElements();
for
(
int
index = 0; index < numberOfElementsIna; index++)
total = total + a.getElement(index);
if
(numberOfElementsIna > 0)
{
return
(total/numberOfElementsIna);
}
else
{