email me at borlaj@portlandschools.org
notes previous (09/07/06) submit the dump links  
 

Random Action

 

Math.random(): 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 could use:

 

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 integers 1-6

int randomValue = (int)(6 * Math.random()+1);

For random color:

     public Color findRandomColor()
     {
            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);
            return randomColor;
     }
              

Lets make some useful methods that find a random integer from 1 to Num

public int findRandom (int low, int high)
    {
        int num = (int) (Math.random()*(high-low+1))+low;
        return num;
    }