Generating a Random Number between 1 and 10 Java

Shania picture Shania · Dec 5, 2013 · Viewed 1M times · Source

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?

Answer

Malcolm picture Malcolm · Dec 5, 2013

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