: generates a random
number between 0 and 1 (0<=x<1). ie .456 or .978
If you wanted a random integer between 0 and 100 (inclusive), we
int randomValue = (int)(101 * Math.random());
the statement 101*Math.random() will give us a random number
(with decimals between 0 (including) to 101 (not including).
remember - (int) is a quick way to convert it from a double to
an integer by just cutting off the decimals.
A few more examples
1. Lets say we want a random integer between 1 and 100.
int randomValue = (int)(100 * Math.random()+1);
2. Let say I wanted to simulate a dice rolling: Hence we want
int randomValue = (int)(6 * Math.random()+1);
For random color:
int red= (int)(256 * Math.random());
int green= (int)(256 * Math.random());
int blue= (int)(256 * Math.random());
Color randomColor=new Color(red,green,blue);
Lets make some useful methods that find a random integer from 1 to Num
//This method will find a random integer from start to end inclusive
public int findRandom (int start, int end)
int multiplier = end-start+1;
int random = (int) (Math.random()*multiplier)+start;