I am trying to save random numbers in an array
I have tried this bot it gives me an error (A constant value is expected Code CS0150)
`
int x = 0;
Random rnd = new Random();
int[] cards;
while (x != 5)
{
cards =new int[x] { rnd.Next() };
Console.WriteLine(cards[x]);
x ;
}
`
CodePudding user response:
Currently you're creating a new array on every iteration. I assume you want cards[x] = rnd.Next()
within the loop, and int[] cards = new int[5]
directly before the loop:
int x = 0;
Random rnd = new Random();
int[] cards = new int[5];
while (x != 5)
{
cards[x] = rnd.Next();
Console.WriteLine(cards[x]);
x ;
}
CodePudding user response:
I've made a List instead of an Array so I can use an undefined number of cards `
int x = 0;
Random rnd = new Random();
List<int> cards = new List<int>();
while (x != 5)
{
cards.Add(rnd.Next());
Console.WriteLine(cards[x]);
x ;
}
`
CodePudding user response:
--- Not for Points ---
If you're going to use a List<>
, then use the Count
property:
Random rnd = new Random();
List<int> cards = new List<int>();
while (cards.Count < 5)
{
cards.Add(rnd.Next());
Console.WriteLine(cards[cards.Count-1]);
}
If you're going to use an Array
, then use a for
loop and the Length
property:
Random rnd = new Random();
int[] cards = new int[5];
for(int x=0; x<cards.Length; x )
{
cards[x] = rnd.Next();
Console.WriteLine(cards[x]);
}