clink
clink

Reputation: 213

Rolling two dice and returning count

I'm writing a java program to simulate rolling of two dices. For each roll, if both dice does not have the same face, i increment a counter. Until when both dice have the same face, i want to print out the counter value. Count is basically counting how many times it took to achieve the same faces on both dices.

I tried writing:

int count = 0;

while (true) {
    int dice1 = getRandom(1,6);
    int dice2 = getRandom(1,6);

    if (dice1 != dice2) {
        count ++;
    }
System.out.println(count);

The code doesn't seem to produce the correct output. I'm curious if I'm simulating it correctly based on my logic? I'm new to java and would appreciate some help on this.

The getRandom() function returns a random number between 1 and 6 since a dice can have 1 to 6 values.

private static int getRandom(int n1, int n2){
    int retVal = 0;

    retVal = n1 + (int) Math.floor(Math.random() * (n2 - n1 + 1));

    return retVal;
}

Upvotes: 1

Views: 2025

Answers (3)

M. Shaikh
M. Shaikh

Reputation: 21

import java.util.Scanner;
public class Dice
{

public static void main(String[] args)
{
        Scanner myInput=new Scanner(System.in);
        System.out.print("Tell me how many rolls of dice you would like to see");
        int numRolls=myInput.nextInt();

        //create array based on rolls
        int [] diceArray=new int[13];
        int diceRoll1;
        int diceRoll2;
        for(int index=0;index < numRolls;index++)
        {
            //diceArray[index]=(int)(Math.random()*11)+2;
            diceRoll1=(int)(Math.random()*6)+1;
            diceRoll2=(int)(Math.random()*6)+1;
            diceArray[diceRoll1]++;
        }
        for(int index=2;index<diceArray.length;index++)
        {
            //System.out.println(diceArray[index]);
            System.out.println(index + " " + diceArray[diceRoll1]);
        }
}

}

Upvotes: 1

user9420984
user9420984

Reputation:

You are almost there!

The problem you are facing is that you are never terminating your while loop. You will need something like this:

int count = 0;
boolean roll = true;
while (roll) {
    int dice1 = getRandom(1,6);
    int dice2 = getRandom(1,6);

    if (dice1 != dice2) {
        count ++;
    } else {
       roll = false;
}
System.out.println(count);

I added a boolean which states if a dice should be rolled. Once the two dices have an equal value, roll is set to false and the loop terminates.

Upvotes: 2

Eran
Eran

Reputation: 393771

You are always printing the count. You should only print the count when the numbers are equal, as which point you should probably break out of the loop:

while (true) {
    int dice1 = getRandom(1,6);
    int dice2 = getRandom(1,6);

    if (dice1 != dice2) {
        count++;
    } else {
        break;
    }
}
System.out.println(count);

Upvotes: 2

Related Questions