Dice Simulation for loop does not satisfy requirements

Viewed 31

I'm making a dice simulation program, and I'm using a for loop to count the number of rolls up to 10,000. However, the program outputs a total number of rolls that are way less than 10,000 (~1,500). Can anybody help me figure out whats wrong?

      int die1Value;       // Value of the first die
      int die2Value;       // Value of the second die
      int count = 0;       // Total number of dice rolls
      int snakeEyes = 0;   // Number of snake eyes rolls
      int twos = 0;        // Number of double two rolls
      int threes = 0;      // Number of double three rolls
      int fours = 0;       // Number of double four rolls
      int fives = 0;       // Number of double five rolls
      int sixes = 0;       // Number of double six rolls

for (count = 0; count<10000; count++){
          int min= 1;
          int max= 6;
          die1Value = generator.nextInt((max - min) + 1) + min;
          die2Value = generator.nextInt((max - min) + 1) + min;
          if (die1Value == die2Value){
                if (die1Value==1) {
                    snakeEyes++;}
                else if (die1Value==2) {
                    twos++;}
                else if (die1Value==3) {
                    threes++;}
                else if (die1Value==4) {
                    fours++;}
                else if (die1Value==5) {
                    fives++;}
                else if (die1Value==6) {
                    sixes++;}               
                count++;          
          }
      }
2 Answers

You are incrementing the counter not only in the for loop definition, but also when both dies have the same value. Which should happen around 1600 times. Remove the second count++; (in the if block).

  1. You are incrementing count whenever die1Value == die2Value. That will have the effect of skipping the next throw when doubles are thrown.

  2. The sum of snakeEyes, twos, threes, fours, fives, and sixes will be the sum of doubles. It will be less than the total number of throws. If you want to verify the totals, add a variable other or nonDoubles , and increment it when die1Value == die2Value returns false.

Off topic: You can use an array to shorten your code:

  int [] doublesCount = new int [6]; // initialize to zeros
  int othersCount = 0;
  ... 
      if (die1Value == die2Value) {
          doublesCount[die1Value - 1]++;
      } else {
          othersCount++;
      }

  


  
Related