Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Rolling two dice until you get a desired sum

Tags:

java

dice

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

like image 624
Ryan Avatar asked Jan 30 '23 20:01

Ryan


1 Answers

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
like image 193
Naman Avatar answered Feb 02 '23 10:02

Naman