Random numbers

Random numbers are extremely useful and important. They are used in almost every game to set chances of things happening (think dice rolls, etc), as well as in cryptography.

As in many things in Java, there is more than one way to make random numbers.

Method 1: use Math.random

	double d = Math.random();		//this does the standard thing and returns a double between 0 and 0.99999
	int r = (int)(Math.random() * n) + 1;  //this makes random integers from 1 to n

How it works:

Method 2: make a Random object

	import java.util.Random;
	Random randGen = new Random();		//DO NOT make a new randGen for each number.
	int r1 = randGen.nextInt();		//any valid integer (i.e. from  -2,147,483,648 to 2,147,483,647)
	int r2 = randGen.nextInt( n );		// any integer from 0 to n-1
	int r2 = randGen.nextInt(100) +1;	// an integer from 1 to 100
	double r3 = randGen.nextDouble();	//this does the standard thing and returns a double between 0 and 0.99999.
	//once you've created your Random object (randGen) and your r2 variable,
	//each time you want a new random number, just type
	r2 = randGen.nextInt(100) +1

Method 3:

For super random numbers, use java.security.SecureRandom. It's good to know this if you need to do anything involving securely transmitting information over the internet.


Neither method gives you random integers between n1 and n2.
Neither method gives you random integers spaced out, e.g. random multiples of 3 between 1 and 100.
For both of these situations you have to do the math yourself.

I use Math.random() because it's shorter: int rand = (int)(Math.random() * 10) + 1;

Here's the identical code for util.Random, which a lot of people still use:
import java.util.Random; Random randgen = new Random(); int rand = randGen.nextInt(10) + 1;