Java: roll two dice until you get the amount you want

I want to write a program in which I discard two dies until I get the sum of those dice equal to 11. I want to record how many "tries" or rolls of dice I have used by the time I received the sum of 11.

My code:

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 on typing that it took 1 roll to get the total of 11, so something is wrong.

My goal: Player 1 rolls 2 all the time until I get 11 and write down how many tries it took. Then ask Player 2 to do the same. Then which player has fewer tries "wins" the game.

Help rate thanks newbie

+3


source to share


2 answers


You might want to update your state

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

      

+8


source


Note that this Math.random()

returns a floating point number 0 <= x <= 1.0

( Java API docs Math.random () ). So the maximum value of your formula is:

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

      



is equal to 7.

+1


source







All Articles