Generating Random Numbers


Random rn = new Random(); int value = rn.nextInt(); double dvalue = rn.nextDouble();



To generate random numbers, we use the Random class found in the java.util package. By default, the Random class uses the current time of day as a seed value for its random number generator. You can also set a seed value by passing it as a parameter to the constructor of Random. The nextInt() method will produce a 32-bit integer random number.

An alternate way of generating random numbers is to use the random() method of the Math class in the java.lang package.

double value = Math.random();


This method will return a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. To generate a value within a specific range, you could add the lower bound to the result of Math.random() and multiply by the range. For example, the following code would give us a random number between 5 and 20:

double value = (5+Math.random())*15;


The Random class and the random() method of the Math class will actually give you a pseudorandom number, not a true random number. This means that the random number is generated using a mathematical formula and an input seed value. Given the seed value and knowledge of the inner workings of the Random class, it would be possible to predict these random values. Therefore, these classes are probably not the best solution for a random number generator for use in high security applications. For most applications, though, these are perfectly acceptable random number generators.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

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