Java Reference
In-Depth Information
dice =
new
Die [ numberOfDice ] ;
for
(
int
i=0;i
<
numberOfDice ;
i++)
{
dice[i] =
new
Die () ;
}
}
public
DiceCup(
int
numberOfDice ,
int
numberOfSides)
{
this
. numberOfDice = numberOfDice ;
dice =
new
Die [ numberOfDice ] ;
for
(
int
i=0;i
<
numberOfDice ; i++)
{
dice[i] =
new
Die(numberOfSides) ;
}
}
public
String toString()
{
String result =
"Your dice are: "
;
for
(Die d: dice)
{
result += d+
""
;
return
result ;
}
public boolean
isYahtzee()
{
for
(Die d: dice)
{
if
(! d.equals(dice [0]))
{
return false
;
}
return true
;
}
public void
rollDice(
int
[ ] diceToChange)
{
for
(
int
i : diceToChange)
{
dice [ i
−
1].rollDie() ;
}
}
}
We have created two constructors for the class. The first constructor uses the default
number of dice and the default number of sides for every die. The second constructor uses
the values of the input parameters to set these values. Note that the memory for the array
of dice is allocated inside the constructors. The reason is that initially we do not know the
size of the array.
When an array of objects is created, the
new
keyword needs to be used multiple
times. It needs to be used once to create the array and then once for every object of
the array.
The
toString
,
isYahtzee
,and
rollDice
methods from the previous chapter are now
instance (i.e., non-static). This allows us to create multiple objects of type
DiceCup
,where
every dice cup can have different dice inside.
The
isYahtzee
method now uses the
equals
method of the
Die
class to determine if
two dice are equal. This is a very powerful approach. For example, we can define deuces to