-1

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

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182

2 Answers2

2

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

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
1

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;
}
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
  • You make mistake when initialize random in GetRandomsAsString, your function will generate non unique string when call over short periods of time – Lana Mar 29 '19 at 05:39
  • @SvetlanaMeleshkina What mistake have I done, besides the way that `Random` works? If the OP wants to generate randoms in a short interval of time, that is [another question](https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number). – meJustAndrew Mar 29 '19 at 05:45