AP Computer Science Java: Lesson 3.4
Repetitive Statements - Random Integers


Lesson 3.4 - Random Integers

Purpose: To learn how to declare and use a random integer generator

If you can't beat 'em, random! 
The use of randomness has numerous applications from video games to computerized simulations. In Java, there are a few ways to generate random integers. We will use the random method from Java's Math class.

The Math class random method is used as follows :

   double x = Math.random(); //random decimal from 0-1
  
OR Generate a random number and display it without storing the value:

   System.out.println( Math.random() );

To generate a random integer from 0 to n-1
:

   int y = (int) (n * Math.random());

OR more usefully, we generate a random integer from 1 to n:

   int y = (int) (n * Math.random()) + 1;

In general, to generate a random integer between a and b:

   int y = (int) ((b-a+1) * Math.random()) + a;
 

In closing
, The Math class random method generates decimal values. To get the necessary integer for a program, use the appropriate formula as follows:
     1.  0 to n-1 : (int) (n * Math.random())
     2.  1 to n   : (int) (n * Math.random()) + 1
     3.  a to b   : (int) ((b-a+1) * Math.random()
) + a


 
© DanShuster.com