4

I want to write a program where I roll two die, until I get the sum of those dice being 11. I want to record how many "attempts" or rolls of the dice I used by the time I got the sum of 11.

My code so far:

public class Dice {

    public static void main(String[] args) {

    int counter1 = 0; //Amount of rolls player 1 took to get sum of 9
    int P1sum = 0;

    do {
        int P1Die1 = (int)(Math.random()*6)+1;
        int P1Die2 = (int)(Math.random()*6)+1;  
        P1sum = (P1Die1 + P1Die2);
        counter1++;
    } while (P1sum == 11);

        System.out.println("Player 1 took "+counter1+" amount of rolls to have a sum of 11.");  
    }
}

It just keeps printing that it took 1 roll to get a sum of 11, so something's not right.

My goal: Have player 1 keep rolling 2 die until I get a sum of 11, and record how many tries it took. Then have player 2 do the same. Then whichever player has the lower amount of tries "wins" the game.

Help appreciated thanks im a newbie

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
Ryan
  • 45
  • 1
  • 5

2 Answers2

7

You might want to update your condition

while (P1sum == 11) // this results in false and exit anytime your sum is not 11

to

while (P1sum != 11) // this would execute the loop until your sum is 11
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
Naman
  • 27,789
  • 26
  • 218
  • 353
1

Consider, that Math.random() returns floating point number 0 <= x <= 1.0 (Java API docs Math.random()). So, the maximum value of your formula:

(int)(Math.random()*6)+1;

equals to 7.

Ignatius
  • 1,167
  • 2
  • 21
  • 30