The problem
Craps is a popular dice game played in casinos. Write a program to play a variation of the game, as follows: Roll two dice. Each die has six faces representing values 1, 2, . . ., and 6, respectively. Check the sum of the two dice. If the sum is 2, 3, or 12 (called craps), you lose; if the sum is 7 or 11 (called natural), you win; if the sum is another value (i.e., 4, 5, 6, 8, 9, or 10), a point is established. Continue to roll the dice until either a 7 or the same point value is rolled. If 7 is rolled, you lose. Otherwise, you win.
Breaking it down
public static void main(String[] args) {
int roll1 = rollIt();
int roll2 = rollIt();
System.out.println("You rolled " + roll1 + " + " + roll2 + " = "
+ (roll1 + roll2));
if (getOutput(roll1 + roll2).equals("You win.")) {
System.out.println(getOutput(roll1 + roll2));
} else {
int newRoll = 0;
do {
newRoll = rollIt() + rollIt();
System.out.println("Keep rolling... You just rolled a "
+ newRoll);
} while (newRoll != 7 && newRoll != (roll1 + roll2));
}
}
public static String getOutput(int n) {
if (n == 7 || n == 11)
return "You win.";
if (n == 2 || n == 3 || n == 12)
return "You lose.";
return "point is " + n;
}
public static int rollIt() {
return (int) (Math.random() * 6 + 1);
}
Output
You rolled 6 + 6 = 12
Keep rolling... You just rolled a 6
Keep rolling... You just rolled a 8
Keep rolling... You just rolled a 8
Keep rolling... You just rolled a 5
Keep rolling... You just rolled a 6
Keep rolling... You just rolled a 4
Keep rolling... You just rolled a 4
Keep rolling... You just rolled a 7