Return-Path: Received: from pacific-carrier-annex.mit.edu by po10.mit.edu (8.9.2/4.7) id SAA10191; Tue, 25 Sep 2001 18:57:55 -0400 (EDT) Received: from hermes.java.sun.com (hermes-db.java.sun.com [204.160.241.157]) by pacific-carrier-annex.mit.edu (8.9.2/8.9.2) with SMTP id SAA15474 for ; Tue, 25 Sep 2001 18:53:51 -0400 (EDT) Message-Id: <200109252253.SAA15474@pacific-carrier-annex.mit.edu> Date: Tue, 25 Sep 2001 15:53:51 PDT From: "JDC Tech Tips" To: alexp@MIT.EDU Subject: JDC Tech Tips September 25, 2001 Precedence: junk Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Mailer: Beyond Email 2.2 J D C T E C H T I P S TIPS, TECHNIQUES, AND SAMPLE CODE WELCOME to the Java Developer Connection(sm) (JDC) Tech Tips, September 25, 2001. This issue covers: * Generating Integer Random Numbers * Displaying Element-Level Tool Tips for Swing Components These tips were developed using Java(tm) 2 SDK, Standard Edition, v 1.3. This issue of the JDC Tech Tips is written by John Zukowski, president of JZ Ventures, Inc. (http://www.jzventures.com). You can view this issue of the Tech Tips on the Web at http://java.sun.com/jdc/JDCTechTips/2001/tt0925.html - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GENERATING INTEGER RANDOM NUMBERS There are many ways to generate random numbers with the base libraries found in the Java 2 SDK, Standard Edition. If you haven't kept up to date with changes to the libraries, you might be using an inefficient mechanism or, possibly worse, getting results that are not uniformly distributed. Here's a look at a good way to generate integer random numbers, and then a look at what's not so good about some other ways. The java.util.Random class has been available for generating random numbers since the initial release of the system libraries. Starting with the 1.2 release of the Java 2 SDK, Standard Edition, the Random class has a nextInt() method that accepts an integer argument: public int nextInt(int n) Given some value n, nextInt(n) returns a value greater than or equal to zero but less then that value: 0 <= nextInt(n) < n. All you have to do is create a Random object first, then call nextInt(n) to return the next random int value. Here's a demonstration. The following code snippet generates a large set of random numbers and prints out the average: int count = 1000000; int range = Integer.MAX_VALUE / 3 * 2; double sum = 0; Random rand = new Random(); for (int i=0; i