Generating a Random Number between 1 and 10 Java [duplicate]

Is there a way to tell what to put in the parenthesis () when calling the nextInt method and what to add?

152k 96 96 gold badges 420 420 silver badges 335 335 bronze badges asked Dec 5, 2013 at 1:51 2,515 3 3 gold badges 14 14 silver badges 11 11 bronze badges Did you read the documentation, which explains exactly how to use this function? Commented Dec 5, 2013 at 1:52 @SLaks I actually did, I was still confused after. Commented Dec 5, 2013 at 3:55 You can just put it in your code: int randomNumber = ThreadLocalRandom.current().nextInt(1, 10 + 1); Commented May 21, 2017 at 19:35 Commented Sep 27, 2017 at 12:41

System.out.println( (int)(Math.random() * (max-min+1) + min)) I use this to generate a random number between min and max inclusively

Commented Jan 20, 2022 at 8:14

3 Answers 3

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 
answered Dec 5, 2013 at 1:54 41.4k 11 11 gold badges 70 70 silver badges 92 92 bronze badges java.util.Random Commented Jun 16, 2016 at 21:55 see code here - grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/… Commented Sep 27, 2017 at 12:41 new Random().nextInt(max - min + 1) + min Commented Jul 14, 2021 at 10:00 or use this: System.out.println( (int)(Math.random() * (max-min+1) + min)) Commented Jan 20, 2022 at 8:16

The standard way to do this is as follows:

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.