Thursday 15 April 2010

swing - Java Math.random not random in while loop -



swing - Java Math.random not random in while loop -

this question has reply here:

math.random, generating 0? 5 answers

i running next code random (x, y) coordinate pairs. however, same pair on , on 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 new java, please tell me simple way prepare this. give thanks you!

math.random() returns value between 0.0 , 1.0 exclusive. java evaluates left right causing (int)math.random() evaluated first truncating value 0 x3 , y3 evaluated as

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

surround first term of assignment in parenthesis

int x3 = (int) (math.random() * 831) + 50; int y3 = (int) (math.random() * 381) + 50;

java swing random while-loop

No comments:

Post a Comment