## Solution for Programmming Exercise 3.1

This page contains a sample solution to one of the exercises from Introduction to Programming Using Java.

### Exercise 3.1:

How many times do you have to roll a pair of dice before they come up snake eyes? You could do the experiment by rolling the dice by hand. Write a computer program that simulates the experiment. The program should report the number of rolls that it makes before the dice come up snake eyes. (Note: "Snake eyes" means that both dice show a value of 1.) Exercise 2.2 explained how to simulate rolling a pair of dice.

**Discussion**

Since we want to roll the dice at least once, a do..while is appropriate. A pseudocode algorithm for the program is

Let countRolls = 0 do: roll the dice count this roll by adding 1 to countRolls while the roll is not snake eyes Output the value of countRolls

As in Exercise 2.2, we can simulate rolling one die by computing (int)(Math.random()*6) + 1.

We want to **stop** rolling the dice when the roll is a double
1. We want to **continue** rolling the dice while the roll is
**not** a double 1. If die1 and die2 are
variables representing the values of the dice, the condition for continuing to
roll can be expressed as

while ( ! (die1 == 1 && die2 == 1) )

The exclamation point means "not", so the condition says that it is not the
case that both die1 is 1 and die2 is 1. That is, it is not
the case that the dice came up snake eyes. Another way to express the same
condition is that at least one of the dice is not 1, that is, that either
die1 is not 1 **or** die2 is not 1. In java
code, this is written:

while ( die1 != 1 || die2 != 1 )

This is the test that I use in my program. Students often get the && and || operators mixed up, especially when negation is involved. (In this case, we could have avoided the problem by testing while (die1+die2 != 2).)

Filling in some details gives an algorithm that can be easily converted into a program:

Let countRolls = 0 do: die1 = (int)(Math.random()*6) + 1 die2 = (int)(Math.random()*6) + 1 count this roll by adding 1 to countRolls while die1 is not 1 or die2 is not 1 Output the value of countRolls

**The Solution**

public class SnakeEyes { /* This program simulates rolling a pair of dice until they come up snake eyes. It reports how many rolls were needed. */ public static void main(String[] args) { int die1, die2; // The values rolled on the two dice. int countRolls; // Used to count the number of rolls. countRolls = 0; do { die1 = (int)(Math.random()*6) + 1; // roll the dice die2 = (int)(Math.random()*6) + 1; countRolls++; // and count this roll } while ( die1 != 1 || die2 != 1 ); System.out.println("It took " + countRolls + " rolls to get snake eyes."); } // end main() } // end class