0 votes
1 view
in Java by (4.1k points)

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?

1 Answer

0 votes
by (46.1k points)

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

Related questions

0 votes
1 answer
asked Jul 20, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Sep 10, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !