Reputation: 249
Main class for this project is acm.program.GraphicsProgram;
GraphicsProgram
When working on my project earlier i needed to randomize ball movement slightly in Pong game and found solution to this by using import java.util.Random;
and then i used this code (executed every time ball bounces off player's paddle, this makes the ball move differently every game):
Random rand = new Random();
boolean bool = rand.nextBoolean();
if (bool)
if (dx > 0)
dx += 1;
else
dx -= 1;
else if (dy > 0)
dy += 0.5;
else
dy -= 0.5;
where dx
and dy
are respectively ball horizontal and veritcal speeds.
But today during lecture on university we've been shown different method (not related to the 1st one, i figured that one myself earier), using
import acm.util.RandomGenerator;
and then
RandomGenerator rgen = RandomGenerator.getInstance();
boolean bool = rgen.nextBoolean();
Is there any difference between these two classes (Random and RandomGenerator)? If so, which one is better to use? I don't quite understand what getInstance();
is and why I didn't need one when using Random
class.
Upvotes: 1
Views: 3720
Reputation: 269847
The ACM RandomGenerator
has a few extra conveniences methods, like nextColor()
to pick a random color.
It also provides a global generator, via its getInstance()
class method. Based on the comments, it sounds like the constructor uses the current time as a seed. This is a big flaw, and can result in a bug where different generator instances produce the same sequence of random numbers. To work around this, they recommend using just one instance of RandomGenerator
, accessed via the getInstance()
method.
In general, it would be best to use java.util.Random
, because it doesn't introduce a third-party dependency in your program, and it uses a better seeding algorithm that isn't subject to the flaws of the ACM implementation.
Upvotes: 5