I generated 10 random numbers and put it in array V0(9) but I have problem to display the array numbers in listbox.
Randomize()
For i = 0 To 9
i = 0
V0(i) = Rnd()
Next
For i = 0 To 9
i = 0
ListBox1.Items.Add(V0(i))
Next
Can help with my code??
Printable View
I generated 10 random numbers and put it in array V0(9) but I have problem to display the array numbers in listbox.
Randomize()
For i = 0 To 9
i = 0
V0(i) = Rnd()
Next
For i = 0 To 9
i = 0
ListBox1.Items.Add(V0(i))
Next
Can help with my code??
First up, don't use Randomize and Rnd in VB.NET. Use the Random class instead.
As for your issue, get rid of this line in your loops:The whole point of the loops is for 'i' to take the values from 0 to 9, so why would you set 'i' to 0 every single iteration? As it stands, you're setting the first element in the array to a random number 10 times, so only the last one will be remembered, then you're adding the first element of the array to the ListBox 10 times. The result is that you'll see the tenth random number in the ListBox ten times. That code should be:vb.net Code:
i = 0Note that I used NextDouble in that code because it's equivalent to what you were doing, but that's going to generate Double values in the range (0.0 <= N < 1.0). Is that what you really want?vb.net Code:
Dim rand As New Random For i = 0 To 9 V0(i) = rand.NextDouble() Next For i = 0 To 9 ListBox1.Items.Add(V0(i)) Next
Also, you can replace the second loop with a single line of code:Finally, I'd suggest using descriptive variable names. 'V0' is generally not a good variable name. For any variable that isn't used solely within a small section of code, the name should generally consist of at least one full word that describes the purpose of the variable.vb.net Code:
ListBox1.Items.AddRange(V0)
But I wanted to generates 10 numbers from 0 to 9.
Is there any other ways to generates random numbers???
For i = 0 To 9
V0(i) = rand.Next()
Next
This code can generates integers but sometimes it don't generates 10 integers.
Yes it does generate 10 Integers. It's just that some of them may be repeated. You aren't placing any restrictions on the values so there's no reason that values wouldn't be repeated. At no point did you say that you wanted unique values or that you didn't want values repeated. If you don't tell us what you want then you'll likely not get it. What you should have said was something like "I want the then numbers 0 to 9 in an array in random order.
The correct way to generate the random numbers on this case is with the random class. You just need to do so in a way that will allow you to get the result you want. In .NET 3.5 it would be fairly succinct because you can use LINQ:In earlier versions it's a bit more involved. Follow the CodeBank link in my signature and check out my thread on Unique Random Selections.vb.net Code:
Dim rng As New Random Dim numbers = (From n In Enumerable.Range(0, 10) _ Order By rng.NextDouble()).ToArray()