Reputation: 19
I want to create an int array that hold 10
numbers that range from (0-9
). Then I want the array to output 3
different numbers.
I made one but it only gives me one random number. How can I fix this so it outputs three numbers instead of one.
int[] password = { 0,1,2,3,4,5,6,7,8,9 };
Random r = new Random();
int inputPassword = r.Next(password.Length);
Console.WriteLine(inputPassword);
Upvotes: 0
Views: 161
Reputation: 62078
Unless, at some point, you are planning to change the numbers in the array to something different, then the array is completely unnecessary - other than its length property, which is fixed, you aren't actually using it.
Based on what you've stated as your goal, the code could be as simple as this:
int n = 10;
int length = 3;
Random r = new Random();
for (int i = 0; i < length; i++)
{
int inputPassword = r.Next(n);
Console.WriteLine(inputPassword);
}
Demo: https://dotnetfiddle.net/OKgqIE
P.S. If there are more constraints to the scenario which make this inadequate then you need to clarify them.
Upvotes: 1
Reputation: 16433
The way to achieve your aim is simple, use a loop of some kind.
In the example below I've used a for
loop:
int[] password = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Random r = new Random();
for (int i = 0; i < 3; i++)
{
int inputPassword = r.Next(password.Length);
Console.WriteLine(inputPassword);
}
Incidentally, as pointed out by @ADyson, you're not actually using any of the stored values in your password
array. The line where you use the Next
random should be like this:
int inputPassword = password[r.Next(password.Length)];
This will fetch the value at a random index
in the password
array.
Upvotes: 2