The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
February 2002

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Random

Posted by Matt Gerrans on February 19, 2002 at 1:00 PM

Here's my version:


import java.util.Random;

public class MyRandom
{
final static Random random = new Random();

static int getTargetNumberToGuess()
{
return random.nextInt(100) + 1;
}
}

The main differences are:


  1. The Random object is static, since you really only need to create it once and use it many times in your program, instead of creating one every time you want a new random number.
  2. It has a more descriptive name, which becomes even more important when it is a class or instance variable.
  3. To get the range of 1 to 100, you need to call nextInt() with the parameter of 100 (which will give a random number from 0 to 99) and then add 1 to it.


> What I suggest is for you to use the java.util.Random class for Random number generation. The code below might help you....

> import java.util.Random;
> public class MyRandom {

> public MyRandom() {
> }
> public static void main(String args[])
> {
> Random x = new Random();
> System.out.println(x.nextInt(101));

> }
> }





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us