Posted By: Anonymous
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?
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
max (including both), you write
random.nextInt(max - min + 1) + min