This question already has an answer here:
I want to generate a number between 1 and 10 in Java.
Here is what I tried:
Random rn = new Random();
int answer = rn.nextInt(10) + 1;
Is there a way to tell what to put in the parenthesis ()
when calling the nextInt method and what to add?
This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.
If you want to test it out try something like this.
Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).
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
tomax
(including both), you writeThe standard way to do this is as follows:
Provide:
and get in return a Integer between min and max, inclusive.
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.