Saturday, 20 August 2016

Chapter 6 Exercise 30, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**6.30 (Game: craps) 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. Your program acts as a single player. Here are some sample runs.

You rolled 5 + 6 = 11
You win
You rolled 1 + 2 = 3
You lose
You rolled 4 + 4 = 8
point is 8
You rolled 6 + 2 = 8
You win
You rolled 3 + 2 = 5
point is 5
You rolled 2 + 5 = 7
You lose

public class ProgrammingExercise6_30 {
 
 public static void main(String[] args) {
  craps();
 }
 
 // Generate random number in integer
 public static int intRandom(int lowerBound, int upperBound) {
  return (int) (lowerBound + Math.random()
    * (upperBound - lowerBound + 1));
 }
 
 public static int roll() {
  int dice1 = intRandom(1, 6);
  int dice2 = intRandom(1, 6);
  int sum = dice1 + dice2;
 
  System.out.println("You roll " + dice1 + " + " + dice2 + " = " + sum);
 
  return sum;
 
 }
 
 public static void craps() {
 
  int first = 0;
 
  // First roll
 
  first = roll();
  // check craps
  switch (first) {
  case 2:
  case 3:
  case 12:
   System.out.println("You lose");
   break;
  case 7:
  case 11:
   System.out.println("You win");
   break;
  default:
   System.out.println("The point is " + first);
   // next roll
   int next;
   do {
    next = roll();
 
   } while (!(next == first || next == 7));
 
   if (next == 7) {
    System.out.println("You lose");
   } else {
    System.out.println("You win");
   }
 
  }
 
 }
 
}

No comments :

Post a Comment