Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Sep 11, 1998

Generating Random Numbers

The java.util package contains a class called Random which you can use to generate random numbers. A Random object represents a repeating pseudo-random sequence of numbers. You can either fetch the next actual pseudo-random number with the next() method or fetch a uniformly distributed float, double, int, or long value using nextFloat(), nextDouble(), nextInt(), or nextLong(). However, you have to convert these uniformly distributed values into something you can use. nextFloat() and nextDouble() return values between 0.0 and 1.0, which can be used to generate random integers in a set range as demonstrated by this example:
 
import java.util.*;

public final class PrintRandom {
  public static final void main(String[] args) {
    Random random;
    double d;
    int minValue, maxValue;

    random = new Random(System.currentTimeMillis());

    minValue = Integer.parseInt(args[0]);
    maxValue = Integer.parseInt(args[1]);

    d = (maxValue - minValue + 1);
    d*=random.nextDouble();

    System.out.println(minValue + (int)d);
  }
}
Daniel Savarese
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date