Java Reference
In-Depth Information
array. The first time the for loop is executed, the variable el will be assigned the first
element of the array. The second time the for loop is executed, the variable will be assigned
the second element of the array and so on. The new code seems cleaner and easier to write
and understand. The only caveat is that a for-each for loopcanbeusedtoreadanarrayof
elements, but not to populate it. For example, it is tempting to apply our new knowledge
of the for-each for loop and rewrite the rollDice method as follows.
public static void rollDice()
for ( int el : dice) {
el = getRandomDieValue () ;
Unfortunately, this rewrite is wrong. It modifies the variable el multiple times, but it does
not change the array in any way. As a general rule, a for-each for loop cannot be used to
modify an array; it can only be used to examine its content. The reason is that it iterates
through an array and it assigns the elements of the array to a variable. Obviously, this in
no way changes the content of the array.
As a different example, the isYahtzee method only examines the dice without modifying
them. Therefore, it can be rewritten as follows.
public static boolean isYahtzee()
for ( int el : dice) {
if (el != dice[0]) {
return false ;
return true ;
As a general rule, use the for-each for loop when you want to examine the content
of an array but you do not want to modify the array. Most of the time, the for-each
for loop is preferred to the regular for loop because it makes the code cleaner and
easier to understand.
We are finally ready to present the first iteration of the Yahtzee game.
import java . util .
public class Yahtzee
static final int NUMBER OF DICE = 5 ;
static final int NUM REROLLS = 2 ;
static int [] dice = new i n t
public static void main(String [] args) {
Scanner keyboard = new Scanner(System. in) ;
rollDice() ;
for ( int i=0;i < NUM REROLLS ;
i ++) {
if (isYahtzee()) {
// no need to continue i f we got Yahtzee
break ;
System.out . println(diceToString()) ; //prints the dice
System. out . print ( "Which dice do you want to reroll: " );
Search WWH ::

Custom Search