2009年10月9日星期五

Random numbers - API

1. java.util.Random class

import java.util.Random; // Only the Random class
Random r = new Random(); // Default seed comes from system time.
int i = r.nextInt(int n); //Returns random int >= 0 and < n
int i = r.nextInt(); //Returns random int (full range)


Example: Generating a number from 1 to 6

Because nextInt(6) returns a number from 0-5, it's necessary to add 1 to scale the number into the range 1-6,

static Random randGen = new Random();
int spots = randGen.nextInt(6) + 1;


2. Math.random() method

The Math.random() method returns random double numbers in the range >=0.0 to <1.0 .
For example, if you need an int int the range 1 to 10, the following code could be used.
int n = (int)(10.0 * Math.random()) + 1;

没有评论:

发表评论