Home How do I generate random integers within a specific range in Java?
Reply: 0

How do I generate random integers within a specific range in Java?

user535
1#
user535 Published in April 24, 2018, 6:45 am

How do I generate a random int value in a specific range?

I have tried the following, but those do not work:

Attempt 1:

randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.

Attempt 2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.501409 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO