Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

5. Numbers > 5.13. Generating Random Numbers

5.13. Generating Random Numbers

Problem

You need to generate random numbers in a hurry.

Solution

Use java.lang.Math.random( ) to generate random numbers. There is no claim that the random values it returns are very good random numbers, however. This code exercises the random( ) method:

// Random1.java 
// java.lang.Math.random( ) is static, don't need to construct Math 
System.out.println("A random from java.lang.Math is " + Math.random( ));

Note that this method only generates double values. If you need integers, you need to scale and round:

/** Generate random ints by asking Random( ) for
 * a series of random integers from 1 to 10, inclusive.
 *
 * @author Ian Darwin, http://www.darwinsys.com/
 * @version $Id: ch05.xml,v 1.5 2004/05/04 20:1:35 ian Exp $
 */
public class RandomInt {
    public static void main(String[] a) {
        Random r = new Random( );
        for (int i=0; i<1000; i++)
            // nextInt(10) goes from 0-9; add 1 for 1-10;
            System.out.println(1+Math.round(r.nextInt(10)));
    }
}

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint