or
Random r = new Random();
int randomInt = r.nextInt(100) + 1;
Answer from MeBigFatGuy on Stack OverflowYou could use e.g. r.nextInt(101)
For a more generic "in between two numbers" use:
Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;
This gives you a random number in between 10 (inclusive) and 100 (exclusive)
Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:
int r = (int) (Math.random() * (upper - lower)) + lower;
Videos
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
Generally speaking, if you need to generate numbers from min to max (including both), you write
random.nextInt(max - min + 1) + min
The standard way to do this is as follows:
Provide:
- min Minimum value
- max Maximum value
and get in return a Integer between min and max, inclusive.
Random rand = new Random();
// nextInt as provided by Random is exclusive of the top value so you need to add 1
int randomNum = rand.nextInt((max - min) + 1) + min;
See the relevant JavaDoc.
As explained by Aurund, Random objects created within a short time of each other will tend to produce similar output, so it would be a good idea to keep the created Random object as a field, rather than in a method.
int max = 100 int min = 5 int randomNum = rand.nextInt((max - min) + 1) + min;
To generate a random number in Java, why is it necessary to have the "+1" ....and in this case why the "+ min" ...this is an example from an online course Im in, and I am just a bit confused about why all these parts of the equation are necessary. What is the simplest way to generate a random number (lets say between 1 and 100) in Java? Thanks for you help and suggestions.