Java Reference
In-Depth Information
public static boolean isYahtzee() {
for ( int i=0;i < NUMBER OF DICE ; i ++) {
if (dice[i] != dice[0]) {
//evidence that dice are different
return false ;
}
else {
return true ;
}
}
}
There are two problems with this rewrite. First, Java will give you a compile error
because the method is not guaranteed to return a value. For example, if NUMBER OF DICE is
equal to zero, then the body of the for loop will not execute. Second, even if you remove
this error by placing “ return true; ” at the end of the method, the method will not return
the correct result. When i is equal to 0, the condition in the if statement will fail and the
method will always return true .
Lastly, we need to write a method that converts the dice to a string. This method is
necessary so that the values of the dice can be displayed. The method starts with the string
"Your dice are: " and then it concatenates all the dice to the string. The implementation
follows.
public static String diceToString() {
String result= "Your dice are: " ;
for ( int i=0; i < NUMBER OF DICE ;
i ++) {
result + =dice[ i]+ "" ;
return result ;
}
We have followed good software practices because the method does just one thing: it
calculates a string representation of the dice. Creating string and printing it in a single
method would be an inferior design because the latter method is more prone to errors and
less reusable.
So far, we have seen a familiar pattern. Every time we want to iterate through the array
of dice, we use the following template.
for ( int i=0; i < NUMBER OF DICE ;
i ++) {
do something with dice [ i ] ;
}
Although the variable i is local to the for loop (it is not defined outside it), it seems
tedious to have to introduce a new variable every time that we want to iterate through the
elements of an array. Defining the variable i globally is an inferior design because it violates
a rule of good software practices: Every variable should be defined only in the block where
it is being used . For convenience, Java supports an alternative way of iterating through the
elements of an array using a for-each for loop . For example, the diceToString method can
be rewritten as follows.
{
public static String diceToString()
String result= "Your dice are: " ;
for ( int el : dice)
{
result + =el+ "" ;
return result ;
}
The statement for(int el: dice) means: iterate through all the elements of the dice
Search WWH ::




Custom Search