Java Reference
In-Depth Information
Now the call
rollDice(new int[]
{
1,2
}
)
will change the first two dice, which seems to
be a more intuitive behavior for the method.
When our program is complete, it should run as demonstrated by the following example
(user input is in italic).
Your dice are: 3,2,5,5,1
Which dice do you want to reroll:
125
Your dice are: 6,5,5,5,4
Which dice do you want to reroll:
15
Your dice are: 5,5,5,5,5
You got Yahtzee!
Therefore, we need a method that parses user input and converts it into an array of
integers. For example, when the user enters: 1 2 5, we want to create the array
{
}
and
send it to the
rollDice
method. Fortunately, a string tokenizer class is part of the Java
library
java.util.*
. Below is an example use of the class.
1
public static int
[] convert(String s)
1,2,5
{
2
StringTokenizer st =
new
StringTokenizer(s) ;
3
int
[] a =
new i n t
[ st . countTokens () ] ;
4
int
i=0;
5
6
while
( st . hasMoreTokens () )
{
7
a[ i++] = Integer . parseInt(st .nextToken()) ;
8
}
9
return
a;
10
}
The first line of the code creates a new string tokenizer object from the string
s
.The
name of the tokenizer is
st
.The
countTokens
method returns the number of tokens in the
string. The
while
loop goes through all the tokens. The
nextToken
method returns the
next token from the string as a
String
,wherethe
Integer.parseInt
method converts the
string to an integer. The
hasMoreTokens
method returns true when there are more tokens
in the string tokenizer. The
convert
method creates an array of integers and returns the
array. For example, the call
covert("1 2 3")
will return the array of integers
.
Note that the above code makes a clever use of the
++
operator. Line 7 uses the syntax
i++
. This means use the current value of
i
and then increment
i
by one later. The first
time Line 7 is executed, the variable
a[0]
will be assigned and
i
will change to 1. This is
exactly the desired behavior.
Our next method will check to see if the dice form a Yahtzee. The method will go through
all the dice and check if they are equal to the first die. If one of the die is not equal to the
first die, then we know that the dice are not all the same and the method will return
false
.
If we go through all the dice and they are all the same, then the method will return
true
.
public static boolean
isYahtzee()
{
for
(
int
i=0;i
<
NUMBER OF DICE ; i ++)
{
if
(dice[i] != dice[0])
{
{
1,2,3
}
//evidence that the dice are different
return false
;
}
return true
;
}
Novice programmers are sometimes tempted to use the
if-else
construct when writing
similar methods. For example, note that the following rewrite is not correct.