Java Reference
In-Depth Information
be wild. In other words, we can define the value 2 to be equal to all the other values in the
Die
class. In this case,
will be considered a Yahtzee.
Let us compare the old and the new versions of the
rollDice
method. The old version
is shown below.
{
5,2,5,2,5
}
public static void
rollDice(
int
[ ] diceToChange)
{
for
(
int
i : diceToChange)
{
dice [ i
−
1] = getRandomDieValue () ;
}
}
The expression
dice[i-1] = getRandomDieValue()
is replaced with
dice[i-1].rollDie()
.
The new expression sends the
dice[i-1]
object as a hidden parameter to the
rollDie
method of the
Die
class, which changes the value of the die.
The new version of the
Yahtzee
class is shown next.
public class
Yahtzee
{
public static final
int
NUMBER REROLLS=2 ;
public static void
main(String [] args)
{
Scanner keyboard =
new
Scanner(System. in) ;
DiceCup dc =
new
DiceCup () ;
System. out . println (dc) ;
for
(
int
i=0;i
<
NUMBER REROLLS ;
i ++)
{
if
(dc.isYahtzee())
{
break
;
System. out . print (
"Which dice do you want to reroll: "
);
dc. rollDice(convert(keyboard.nextLine()));
System. out . println (dc) ;
}
if
(dc.isYahtzee())
{
System. out . println (
"You got Yahtzee!"
);
}
else
{
System. out . println (
"Sorry, better luck next time!"
);
}
}
static int
[] convert(String s)
{
StringTokenizer st =
new
StringTokenizer(s) ;
int
[] a =
new i n t
[ st . countTokens () ] ;
int
i=0;
while
( st . hasMoreTokens () )
{
a[ i++] = Integer . parseInt(st .nextToken()) ;
return
a;
}
}
The
diceToString
method is gone because the to-string conversion now happens in the
toString
method of the
DiceCup
class. This is a better design because the
DiceCup
class
should be responsible for converting an object of type
DiceCup
to a string.