## Trending News

# Visual Basic.NET : How to give a random value between 1 and 100 to a variable?

i'm currently trying to do a little game where you must find a number between 1 and 100 , and i really don't know how to give a number X a random value that would be between those number and to affect it to a variable

### 2 Answers

- peteamsLv 71 decade agoFavorite Answer
.NET, like many frameworks, has a class that internally generates pseudo random numbers from zero to just shy of one. Pseudo random means they're not random at all, just very hard to predict.

.NET's class is called Random and it presents two flavours of a Next function to extract random numbers. To get random numbers from 1 to 100 inclusive you need something like the following:

Dim rnd as Random();

number = Random.Next(1, 101)

Note that you should hold onto one Random object and use it to create all your random numbers, you should not create a new one every time you want a random number, nor should you have several of them (although that is less of a sin).

Also note that if you want numbers 1,2,3...,98,99,100 then you need to use Next(1,101), otherwise you will not get 100 in your output.

When testing it is often useful to 'seed' the random number generator with a constant, e.g.L

Dim rnd as Random(42)

This shows up the pseudo-ness of the random numbers, the generator will always produce the same sequence of numbers. That is bad for actually using the application, but ideal for testing - you really want to make sure you test the same thing every time and that your tests are easily reproducible.

- 1 decade ago
here is the code

Private Function RandomNumber(min as Integer , max as Integer) As Integer

Dim Random As New Random()

Return Random.next(min,max)

End Function

Well in the above code , set min=1 and max=100 as you want to find a number between 1 and 100