Kyle Sayers Kyle Sayers - 10 months ago 47
Java Question

Math.random() Generates same number

I'm writing a generic snake game in Java, and I want my apple to be drawn at random coordinates on call. However, when I set my coordinates based off Math.random(), both coordinates create the same Math.random result. This means the apple is always drawn on a linear line ex. (4,4)

//Draws apple
public void drawApple(Graphics2D gfx) {
rectCoords(gfx, red, (int) Math.floor(Math.random()*20), (int) Math.floor(Math.random()*20));
// rectCoords(graphics, color, xcoordinate, ycoordinate)

I assume this is because they're using the same time value for their seed, since they were called at the same time.

I've tried
objects, even a combination of both. I've tried declaring them as variables at different times throughout the code, even throwing in a
(although I had some trouble actually getting it to work).

Surely I'm not the only one who's tried to generate two random numbers at the same time. I appreciate anyone who looks this over or points me to a similar thread. Thanks!

EDIT: I fixed it, it was a problem in another piece of code. Although, not really sure how to close this thread or mark it resolved...

Answer Source

You will always get a number which is less than 20 with your current code (because Math.random() gives a double value which is >=0 and <1), so instead you can use nextInt() method from java.util.Random as shown below:

public void drawApple(Graphics2D gfx) {
     Random random = new Random();
    rectCoords(gfx, red, random.nextInt(), random.nextInt());

Also, you can actually use the overloaded method nextInt(maxNumber) to set the maximum limit to the random number by using/passing maxNumber value random.nextInt(maxNumber).