Robert Sayegh
Robert Sayegh

Reputation: 3

Beginner coder, stuck with random generator

Here is my code, the object is to tally the number of double 1s, 2s, 3s, ... rolled out of 10,000 rolls. This is what i wrote so far and I cannot figure out why it is tallying up every single roll as a double

while (count < 10000)
{
    Random rand = new Random();  
    die1Value = rand.nextInt(6) + 1;
    die2Value = rand.nextInt(6) + 1;

    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;
    }
}

Feedback would be greatly appreciated.

Upvotes: 0

Views: 75

Answers (2)

Florent Bayle
Florent Bayle

Reputation: 11920

You are incrementing count inside of the if :

if(die1Value == die2Value)
{
    // ...
    ++count;
}

And your while loop is on the count value :

while (count < 10000)

So, what you are effectively doing is discarding every throw where you don't have a double and re-throw it.

Upvotes: 2

Caleryn
Caleryn

Reputation: 1084

because ++count is inside the if(die1Value == die2Value) block

so it will loop as many times as required to find 10000 doubles. probably about 6 times that number.

reformatting the code above shows this more clearly.

Upvotes: 1

Related Questions