Java Reference
In-Depth Information
numerals (e.g., magic numbers, such as 5) to be defined as constants at the beginning of
the code.
Note that Java is lenient as to what can go in the size of an array. In particular, the size
of an array can be a variable that is initialized from keyboard input and does not need to
be a constant. The only restriction is that once an array is created, its size cannot change.
Therefore, make sure that you have enough space to store your data when you declare an
array.
The rollDice method can now be rewritten to use a for loop.
public static void rollDice()
{
for ( int i=0;i
<
NUMBER OF DICE ;
i ++)
{
dice [ i ] = getRandomDieValue () ;
}
} The elegancy in the new approach is that we only need to change the constant
NUMBER OF DICE when we want to change the number of dice. Nothing else needs to be
changed. Next, consider a method that modifies only some of the dice. Remember that in
the Yahtzee game a player is allowed to change some of his or her dice up to two times. Which
dice to change can be specified as a parameter to the method. One possible implantation
of the method follows.
public static void rollDice( int [ ] diceToChange) {
for ( int i=0; i < ? ; i ++) {
dice [ diceToChange [ i ]]=getRandomDieValue() ;
}
} Note that it is perfectly fine to have two methods that are named rollDice .Ifthe
rollDice method is called without a parameter, then the first implementation will be
called and all the dice will be rerolled. Conversely, if the method is called with an array of
integers as a parameter, then the second method will be called and only the chosen dice
will be rerolled. The question mark in the above code is not a new Java feature. The size
of the array diceToChange should appear there, but how can we find the size of the array?
Fortunately, Java allows us to find the size of the a array by writing a.length . Therefore,
the code should actually read as shown below.
public static void rollDice( int [ ] diceToChange) {
for ( int i=0; i < diceToChange . length ; i++) {
dice [ diceToChange [ i ]]=getRandomDieValue() ;
}
}
{
}
) .Thiscode
will change the value of the first, third, and fifth die (remember that the first element of an
array is at index 0). The code is an example of creating an anonymous array . The statement
new int[] { 0,2,4 }
An example invocation of the method is: rollDice(new int[]
0,2,4
. However, this
arrayisnotsavedinavariableandwecannotrefertoit.Itissimplypassedasanargument
to the method.
If we are more comfortable counting dice starting with die 1, rather than die 0, then we
can rewrite the method as follows.
public static void rollDice( int [ ] diceToChange)
creates an array of three integers with values
{
0,2,4
}
{
for ( int i=0;i < diceToChange . length ; i++) {
dice [ diceToChange [ i ] 1] = getRandomDieValue () ;
}
}
Search WWH ::




Custom Search