Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

random

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?

like image 910
Shania Avatar asked Dec 05 '13 01:12

Shania


People also ask

How do you generate a random number between 1 and 10 using Java random?

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);

Which line will generate a random number between 1 to 10?

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.

How do you generate a random number between two numbers in Java random?

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.


2 Answers

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 
like image 144
Malcolm Avatar answered Oct 08 '22 16:10

Malcolm


The standard way to do this is as follows:

Provide:

  • min Minimum value
  • max Maximum value

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.

like image 25
Scary Wombat Avatar answered Oct 08 '22 16:10

Scary Wombat