-1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DieRoller
{
    public class Program
    {
        public static void Main()
        {
            for (int a = 0; a < 20; a = a + 1)
            {
                Console.WriteLine(RollDie());

            }
            Console.ReadLine();
        }

        public static int RollDie()
        {
            Random roll = new Random();
            int test = roll.Next(1, 6 + 1);
            return test;
        }
    }
}

When I execute this code I get the number 4 multiple times or the number 2 multiple times...etc.

Isn't it supposed to execute the RollDie function for each iteration of the loop? and isn't that supposed to yield a different value each time? pls halp!

EDIT: The thing is guys, I need to generate the randomness only inside the RollDie method, and I can't have any arguments for the RollDie method (Basically I have to generate the randomness only using the random method inside the RollDie method), other questions don't address that.

John
  • 45
  • 5
  • 1
    When you create new instances of Random in quick succession they'll often end up with the same seed, resulting in the same values. – Jonathon Chase Aug 28 '18 at 16:22

1 Answers1

1

See comments for explanation of why it doesn't work. Here a possible way to make it work:

public static void Main()
{
    Random roll = new Random();
    for (int a = 0; a < 20; a = a + 1)
    {
        Console.WriteLine(RollDie(roll));

    }
    Console.ReadLine();
}

public static int RollDie(Random roll)
{
    int test = roll.Next(1, 6 + 1);
    return test;
 }

Or, for simplicity, just:

public static void Main()
{
    Random roll = new Random();
    for (int a = 0; a < 20; a = a + 1)
    {
        Console.WriteLine(roll.Next(1, 6 + 1));

    }
    Console.ReadLine();
 }
eye_am_groot
  • 682
  • 6
  • 19