Java Reference
In-Depth Information
60
// display won or lost message
61
if (
gameStatus == Status.WON
)
62
System.out.println( "Player wins" );
63
else
64
System.out.println( "Player loses" );
65
}
66
67
// roll dice, calculate sum and display results
68
public static int rollDice()
69
{
70
// pick random die values
71
int die1 = 1 + randomNumbers.nextInt( 6 ); // first die roll
72
int die2 = 1 + randomNumbers.nextInt( 6 ); // second die roll
73
74
int sum = die1 + die2; // sum of die values
75
76
// display results of this roll
77
System.out.printf( "Player rolled %d + %d = %d%n" ,
78
die1, die2, sum);
79
80
return sum;
81
}
82
} // end class Craps
Player rolled 5 + 6 = 11
Player wins
Player rolled 5 + 4 = 9
Point is 9
Player rolled 4 + 2 = 6
Player rolled 3 + 6 = 9
Player wins
Player rolled 1 + 2 = 3
Player loses
Player rolled 2 + 6 = 8
Point is 8
Player rolled 5 + 1 = 6
Player rolled 2 + 1 = 3
Player rolled 1 + 6 = 7
Player loses
Fig. 6.8 | Craps class simulates the dice game craps. (Part 3 of 3.)
Method rollDice
In the rules of the game, the player must roll two dice on the first and all subsequent rolls.
We declare method rollDice (lines 68-81) to roll the dice and compute and print their
sum. Method rollDice is declared once, but it's called from two places (lines 26 and 50)
in main , which contains the logic for one complete game of craps. Method rollDice takes
 
Search WWH ::




Custom Search