I'm trying to generate 3 random numbers and output it onto a label as an array with 3 in a row. I am just unsure about doing so. So far, I initialized my random value as

Random valueRandom = new Random();

private void Main()
{
    for (int i = 1; i <= gameAmountInteger; i++)
        DoNextNumber(valueRandom);
}

private void DoNextNumber(Random valueRandom)
{
    int int1;
    int1 = valueRandom.Next(0, 1);
    displayLabel.Text = valueRandom.ToString();
}

It should be (range of 0 - 10) 3, 5, 2

2 Answers

2
sujith karivelil On

Few things you are doing wrongly:

valueRandom.Next(0, 1);

Here the first value of the .Next() method indicates the lower bound and the second parameter indicates the upper bound, and you wanted the upper bound as 10 but given as 1. As you wanted to get the random number between 0-10 you have to give as valueRandom.Next(0, 10), which will not include 10 if need to include 10 means have to give it as valueRandom.Next(0, 11).

displayLabel.Text = valueRandom.ToString();

From the DoNextNumber method you are assigning the generated random number to the required UI element, so you will get the last number only in the UI. If you need to get all the numbers displayed means you have to give it as displayLabel.Text = displayLabel.Text + valueRandom.ToString();

Consider duplicates

There are possibilities of getting duplicate numbers while executing the .Next() repeatedly, if duplicates will be an issue in your scenario means you have to keep the outcomes into a collection and check for existence before pushing the newly generated random number to the collection. In this case write the value to the UI after getting the required collection. In that case you can use the code as like this: displayLabel.Text = String.Join(",", randomCollection); where randomCollection is the collection which I mentioned above

1
meJustAndrew On

You should be using valueRandom.Next(0, 10), and I would refactor your code like following:

public static void Main()
{
    displayLabel.Text = GetRandomsAsString(gameAmountInteger);
}

private string GetRandomsAsString(int numberOfrandoms)
{
    var valueRandom = new Random();
    var randoms = "";
    for (int i = 0; i < numberOfrandoms; i++)
    {
        randoms += valueRandom.Next(0, 10);
    }

    return randoms;
}