Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

java - math.random() doesnt create random number


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

(int)Math.random() always returns 0

(int)Math.random() always returns 0 because Math.random() returns a double value from 0 to less than 1 and thus when you cast it, it will always give you 0.

You should cast Math.random() * (max - min + 1) to int as (int) (Math.random() * (max - min + 1)) instead of casting Math.random() to int which gives you 0 and 0 multiplied with anything is 0.

Also, to avoid such a problem, it's always recommended to use Random#nextInt(int bound) e.g.

Random rand = new Random();
int randomX =  rand.nextInt((max - min + 1)) + min;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...