Friday, October 7, 2011

Math.random( )

Sometimes you need to generate a random number. In Java, the easiest way to do this is to invoke Math.random(). This method returns a value from [0 - 1) which means from 0 (inclusive) up to but not including 1 (exclusive). You can adjust the output by multiplying by a constant and then (int) casting the result, to lop off the decimal part.

Here are some examples and what they return:
  • Code: (int)(Math.random() * 10)
    Returns: [0 -   9]

  • Code: (int)(Math.random() * 10) + 1
    Returns: [1 -  10]

  • Code: (int)(Math.random() * 100)
    Returns: [0 -  99]

  • Code: (int)(Math.random() * 100) + 1
    Returns: [1 - 100]
Be very careful with your parentheses: if you do this

(int)Math.random() * 10

the value returned will always be zero.