Question

Im getting a bug where i call for two ints to get randomly generated by the same method but they always return the same number when releasing the code in debug mode

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kortspil
{
public class Kort
{
    public int FåKortNummer()//Get card number
    {
        System.Random KortNummer = new System.Random();
        int kort = KortNummer.Next(1, 14);
        ErKortTrukket(kort);//is drawn
        return kort;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Kort SpillerEt = new Kort();
        Kort SpillerTo = new Kort();
        int SpillerEtKort = SpillerEt.FåKortNummer();//random number 1
        Console.WriteLine("Spiller et har trukket: " + SpillerEtKort.ToString());
        int SpillerToKort = SpillerTo.FåKortNummer(); // random number 2
        Console.WriteLine("Spiller to har trukket: " + SpillerToKort.ToString());
        if (SpillerEtKort <= SpillerToKort)
        {
            Console.WriteLine("Spiller Et vandt denne runde");//player 1 won this round
        }
        else
        {
            Console.WriteLine("Spiller to vandt denne runde");//player 2 won this round
        }
        Console.WriteLine("Tryk Enter for at lukke...");
        Console.ReadLine();
    }
}

}

Was it helpful?

Solution

You're problem is that you are creating two different Random instances. By default, if you do not supply a seed number, the current time will be used as a seed. However, you're code is executing so quickly, that the same time is being used as a seed (because you're code is executing faster than the smallest resolution of the clock), so the number you receive is the same each time.

The best fix is to create only a single instance of Random. For example, you could change your code to:

public class Kort
{
    public static System.Random KortNummer = new System.Random();

    public int FåKortNummer()//Get card number
    {
        int kort = KortNummer.Next(1, 14);
        ErKortTrukket(kort);//is drawn
        return kort;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top