atesh Posted August 21, 2003 Posted August 21, 2003 I'm trying to generate 1,000 random whole numbers from 1 to 100, then put them in a listbox and show how many times each number(1 to 100) was picked randomly. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim rambo As Integer Dim x, y As Integer Dim dist(100) As Integer For x = 1 To 1000 rambo = New System.Random().Next(1, 100) dist(rambo) += 1 Next For y = 1 To 100 ListBox1.Items.Add(y & "-- " & dist(y)) Next End Sub But when using the code above I get all numbers 1 to 100 as -- 0, except the following: 3-- 160, 25-- 241, 48-- 209, 58-- 148, 80-- 242. So what the heck is going on? Thanks alot. Quote To err is human, to really foul things up requires a computer.
*Experts* mutant Posted August 21, 2003 *Experts* Posted August 21, 2003 Dont seed the random generator everytime. Try it like this: Dim r As New Random 'then for every number r.Next(1,100) Quote
atesh Posted August 21, 2003 Author Posted August 21, 2003 but i get error: Object reference not set to an instance of an object. Quote To err is human, to really foul things up requires a computer.
*Experts* mutant Posted August 21, 2003 *Experts* Posted August 21, 2003 What line and what is the code you are using with what I showed you? If the rest is the same and you just added the declaration and used that object it should work. Here is what works: Dim rambo As Integer Dim x, y As Integer Dim dist(100) As Integer Dim r As New Random For x = 1 To 1000 rambo = r.Next(1, 100) dist(rambo) += 1 Next For y = 1 To 100 ListBox1.Items.Add(y & "-- " & dist(y)) Next Quote
atesh Posted August 21, 2003 Author Posted August 21, 2003 that is exactly how my code is but the error on the line: rambo = r.Next(1, 100) Is there an import/inherit required? Quote To err is human, to really foul things up requires a computer.
*Experts* mutant Posted August 22, 2003 *Experts* Posted August 22, 2003 No, the error means that you dont have an instance of the Random object. Are you sure you have the New keyword when declaring your Random object? Quote
atesh Posted August 22, 2003 Author Posted August 22, 2003 that was the case, im sorry about that. It works fine now. thanks again. :) Quote To err is human, to really foul things up requires a computer.
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.