Random generator = new Random();The generator object can be used to generate either integer or floating point random numbers using either the nextInt() or nextFloat() methods, respectively. The integer returned by nextInt could be any valid integer (positive or negative) whereas the number returned by nextFloat is a floating point value between 0 and 1 (up to but not including the 1). Most often the goal of a program is to generate a random integer in some particular range, say 30 to 99 (inclusive). There are two ways to do this:
generator.nextInt(70)will return a numbers between 0 and 69. Next, it may be necessary to shift the numbers must be shifted to a desired range by adding an appropriate value. So, the expression
generator.nextInt(70) + 30will generate a number between 30 and 99.
generator.nextFloat() * 70returns a floating point number between 0 and 70 (up to but not including 70). To get the integer part of the number we use the cast operator:
(int) (generator.nextFloat() * 70)The result of this is an integer between 0 and 69, so, as before
(int) (generator.nextFloat() * 70) + 30shifts the numbers by 30 resulting in numbers between 30 and 99.
Download LuckyNumber.java and run it a few times:
// ************************************************** // LuckyNumber.java // // To generate two random "lucky" numbers // ************************************************** import java.util.Random; public class LuckyNumber { public static void main (String[] args) { Random generator = new Random(); int lucky1, lucky2; // Generate lucky1 (a random integer between 50 and 79) using the nextInt method lucky1 = generator.nextInt(30)+50; // Generate lucky2 (a random integer between 11 and 30) using nextFloat lucky2 = generator.nextInt(20)+11; System.out.println ("Your lucky numbers are " + lucky1 + " and " + lucky2); } }