-1

I've tried everything from YouTube videos to this forum. I used to find always a solution here but now I'm stuck. I need to generate a random number between 39 and 52.

Here's the somewhat source:

case Form1.number.WITHRANDOM:
{
    int i = 0;
    while (i < ammount)
    {
        i++;
        int j = 0;
        string text2 = "";
        while (j < 2)
        {
            string value = Conversions.ToString(this.random.Next(0, text.Length));
            text2 += Conversions.ToString(text[Conversions.ToInteger(value)]);
            j++;
        }
        this.numberList.Add("173" + (The random number) + text2);
    }
    break;
}
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • 3
    I don't see how you could possibly have missed the [**`Random` class**](https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx)? – Visual Vincent Jan 20 '18 at 11:05
  • Please provide a clear problem statement related to the code you are presenting. The code contains a call to `Random.Next()`, thus it's unclear what you are asking. – Ondrej Tucny Jan 20 '18 at 11:10

1 Answers1

1

You should use the Random class. Its Next method returns a random integer within a specified range (between minValue and maxValue):

public virtual int Next(int minValue, int maxValue)

So, in your case, this is the code:

Random random = new Random();
int number = random.Next(39, 52);
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • Microsoft Docs: The Next(Int32, Int32) method allows you to specify the range of the returned random number. However, the maxValue parameter, which specifies the upper range returned number, is an exclusive, not an inclusive, value. This means that the method call Next(0, 100) returns a value between 0 and 99, and not between 0 and 100. – Protiguous Aug 22 '20 at 21:20