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?
For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);
ThreadLocalRandom. current. nextInt() to Generate Random Numbers Between 1 to 10. The last method in our list to get random numbers between 1 and 10 is using the class ThreadLocalRandom that was introduced in JDK 7 for multi-threaded programs.
If you want to create random numbers in the range of integers in Java than best is to use random. nextInt() method it will return all integers with equal probability. You can also use Math. random() method to first create random number as double and than scale that number into int later.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With