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:
- 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.
- It has a more descriptive name, which becomes even more important when it is a class or instance variable.
- 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:
|