Java Reference
In-Depth Information
This program works as follows. The statement in Line 7 creates the array
dice
of 100
elements and each element is a reference to an object of the
class
RollDie
. The
statement in Line 8 creates the array
rollCount
to store the number of times each
number is rolled. The
for
loop in Line 10 instantiates and initializes each element of the
array
dice
. The
for
loop in 16 retrieves the number rolled by each die and also counts
the number of times each number is rolled. This loop also outputs the numbers rolled
with 34 numbers per line. The
for
loop in Line 26 outputs the number of times each
number is rolled and also determines the maximum roll count. The
for
loop in Line 33
outputs the numbers that are rolled the maximum number of times.
List (Optional)
In Chapter 7, we wrote the method
larger
to determine the larger of two numbers.
Similarly, we can write methods to determine the largest of three numbers, four numbers,
five numbers, and so on. Moreover, using the mechanism of method overloading, each of
these methods can be called
largest
. For example, we can write several such methods
with the following headings:
public static double
largest(
double
x,
double
y)
public static double
largest(
double
x,
double
y,
double
z)
public static double
largest(
double
x,
double
y,
double
z,
double
u)
public static double
largest(
double
x,
double
y,
double
z,
double
u,
double
w)
9
However, this requires us to write the definitions of each of these methods. Java simplifies
this by providing a variable length formal parameter (list). The syntax to declare a variable
length formal parameter (list) is:
dataType ... identifier
where
dataType
is the name of a type, such as the primitive data type or a Java class or a
user-defined data type. Note the ellipsis in this syntax; it is part of the syntax. For
example, consider the following formal parameter declaration:
double
... numList
This statement declares
numList
to be a variable length formal parameter. In fact,
numList
is an array wherein each element is of type
double
, and the number of elements
in
list
depends on the number of arguments passed to
numList
.
Search WWH ::
Custom Search