Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generate Random Number Between Two Given Values [duplicate]

I would like to know how to generate a random number between two given values.

I am able to generate a random number with the following:

Random r = new Random();  for(int i = 0; i < a.length; i++){     for(int j = 0; j < a[i].length; j++){         a[i][j] = r.nextInt();     }  } 

However, how can I generate a random number between 0 and 100 (inclusive)?

like image 244
Mus Avatar asked Mar 11 '11 10:03

Mus


People also ask

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.

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

How will you generate a random number which does not get repeated?

We can use either the RAND or RANDBETWEEN functions for this. The RAND function is the fastest because we don't have to specify any arguments. The RAND function returns a random decimal number to the cell. Input the formula =RAND() in the first cell and double-click the fill handle to copy the formula down.


1 Answers

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random(); int low = 10; int high = 100; int result = r.nextInt(high-low) + low; 

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

like image 81
Erik Avatar answered Sep 17 '22 13:09

Erik