Sometimes when programming, we might want to use random numbers:
Random class provides tools to make
To use the
Random class in your program,
java.util.random at the top.
In programming, "random" numbers come from random number generators. We can make a generator by making a new
Random generator = new Random();
It's common to call the Random object
gen, but like all other variables, you can call it whatever you like.
Your generator can produce random numbers in a few different ways:
nextInt(int n): returns a randomly-selected integer between [0, n-1]. For example,
nextInt(10) will return an integer between 0 and 9, inclusive.
generator.nextInt(10); 9 generator.nextInt(10); 7
nextDouble(): returns a randomly-selected
double d between 0 (inclusive) and 1 (exclusive), so that
0 <= d < 1
generator.nextDouble(); 0.2488107901176655 generator.nextDouble(); 0.09949381836031079
nextInt(): returns an integer between [
generator.nextInt(); 49370236 generator.nextInt(); -22997583
The official Java documentation have information for the Random class' other methods.