Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Random zero argument enquiry

Tags:

java

I am trying to code a game following instructions contained in an OU TMA document which read:

In the constructor, write code to assign a new instance of Random to ran which you should create using the Random class's zero argument constructor

Will this code work?

Random ran = new Random(0) ;

I am a relative newbie to Java, and I don't understand exactly what the instructions mean

like image 876
deerb Avatar asked May 23 '10 07:05

deerb


1 Answers

No, that wont work. A zero-argument constructor is a constructor that takes no arguments:

Random ran = new Random();

is the way to go.

The difference of the two constructors is well described in the API docs:

Random()
Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

Random(long seed)
Creates a new random number generator using a single long seed: public Random(long seed) { setSeed(seed); }

That is, a Random object created with an argument, will return the same sequence of random numbers each run of the program, while an object created through the zero-argument constructor (or, "no argument constructor") will do its best to return different sequences.

like image 62
aioobe Avatar answered Sep 23 '22 03:09

aioobe