Generating a Random Number


Because we want our page to choose a quotation at random, we need to generate a random number. But we don t want just any random number; we want a random number that falls within the range of the elements in our quotations ArrayList object that is, between 0 and the highest element number.

Visual Basic .NET includes a function named Rnd that generates a random number, but it returns a real number (decimal number) between 0 and 1. This value isn t directly useful to us, so we re obliged to go to some extra effort. Here s the code we need:

Dim randomNumber As Intege Randomize( Dim limit As Integer = quotesArrayList.Count     randomNumber = Int((limit + 1) * Rnd()) 

The Randomize statement seeds the random number generator with a starting value using an infinitesimal time slice. We calculate the highest random number we want (the limit) based on the number of elements in the ArrayList object. The complex-looking formula for generating the random number essentially converts the original random number between 0 and 1 to an integer value between 0 and our high limit. This is a standard approach to random numbers it s even described in the Visual Basic .NET documentation. You don t need to understand the details of this approach; you can use it pretty much as-is any time you need a random number, assuming that you set the limit variable appropriately. (Well, you don t want to use the randomizing formula shown here for situations that require industrial-strength randomness, such as in cryptography applications. But for everyday randomness this formula works fine.)




Microsoft ASP. NET Web Matrix Starter Kit
Microsoft ASP.NET Web Matrix Starter Kit (Bpg-Other)
ISBN: 0735618569
EAN: 2147483647
Year: 2003
Pages: 169
Authors: Mike Pope

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net