1

I am running the following code to get random (x, y) coordinate pairs. However, I only get the same pair over and over again.

int counter=0;
while(counter<20){
    x3=(int)Math.random()*831+50;
    y3=(int)Math.random()*381+50;
    canvas.setColor(Color.white);
    canvas.drawString("*", x3, y3);
    counter++;
    }

I am very new to Java, so please tell me a simple way I could fix this. Thank you!

BeastX-Men
  • 13
  • 2

1 Answers1

3

Math.random() returns a value between 0.0 and 1.0 exclusive. Java evaluates from left to right causing (int)Math.random() to be evaluated first truncating the value to 0 so x3 and y3 are evaluated as

x3 = 0 + 50;
y3 = 0 + 50;

Surround the first term of the assignment in parenthesis

int x3 = (int) (Math.random() * 831) + 50;
int y3 = (int) (Math.random() * 381) + 50;
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 2
    Could you please explain *why* the OP should do this? I know this is correct, but the OP should know why his code was incorrect, and yours is correct. – hichris123 Oct 05 '14 at 02:48
  • Is this because (int) makes whatever was right behind an integer? So in my code (int)Math.random is always equal to 0, so x3 and y3 would always be equal to 50? Edit: I just realized this is what the second sentence says, sorry. – BeastX-Men Oct 05 '14 at 05:13