Java Reference
In-Depth Information
2000
main
rollDice
location: 2000
1 3 5
FIGURE 5.2:
Passing an array to a method.
Although not perfect, the above code demonstrates a clean design. Every method is short
and does exactly one thing. The major shortcoming is that methods that do not need to
have access to the array of dice, such as the
convert
method, do anyway. This shortcoming
comes from declaring the array of dice a global variable. As an alternative, the array of dice
can be declared as a local variable in the
main
method and passed to methods that need it.
The new version of the
main
method is shown next.
public static void
main(String [] args)
{
int
[] dice =
new i n t
[ NUMBER OF DICE ] ;
// the dice
Scanner keyboard =
new
Scanner(System. in) ;
rollDice(dice);
for
(
int
i=0;i
<
NUM REROLLS ; i ++)
{
if
(isYahtzee(dice))
{// if we got Yahtzee
break
;
System.out . println(diceToString(dice)) ;
//prints the dice
System. out . print (
"Which dice do you want to reroll: "
);
rollDice(dice ,convert(keyboard.nextLine()));
System.out . println(diceToString(dice)) ;
//prints the dice
if
(isYahtzee(dice))
{
System. out . println (
"You got Yahtzee!"
);
}
else
{
System. out . println (
"Sorry, better luck next time!"
);
}
}
Note that arrays in Java are passed to/from methods using their address. Therefore, the
rollDice
method can and does change the value of the input array. An implementation of
the method is shown below.
public static void
rollDice(
int
[] d)
{
for
(
int
i=0;i
<
NUMBER OF DICE ;
i ++)
{
d[ i ] = getRandomDieValue () ;
}
}
Figure 5.2 shows an example of passing the array to the
rollDice
method. As the figure
suggests, only the number 2000 is passed to the method. This is the location of the array.
Since the
rollDice
method knows this location, it can go to it and modify the content
of the array. Note that this contrasts the way primitive types (e.g., integers, doubles, and
characters) are sent to methods. The latter cannot be modified by a method. For example,
consider the following version of the
rollDice
method.
public static void
rollDice(
int
d0 ,
int
d1 ,
int
d2 ,
int
d3 ,
int
d4)
{