Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a random number in a certain range?

How can I create an app that generates a random number in Android using Eclipse and then show the result in a TextView field? The random number has to be in a range selected by the user. So, the user will input the max and min of the range, and then I will output the answer.

like image 469
user3182651 Avatar asked Jan 10 '14 16:01

user3182651


People also ask

Can Excel generate random numbers within a range?

Select the cell in which you want to get the random numbers. In the active cell, enter =RANDBETWEEN(1,100). Hold the Control key and Press Enter.

How can I generate a random number within a range but exclude some?

After generating the random number you've to put the "holes" back in the range. This can be achieved by incrementing the generated number as long as there are excluded numbers lower than or equal to the generated one. The lower exclude numbers are "holes" in the range before the generated number.


2 Answers

To extend what Rahul Gupta said:

You can use Java function int random = Random.nextInt(n).
This returns a random int in the range [0, n-1].

I.e., to get the range [20, 80] use:

final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80] 

To generalize more:

final int min = 20; final int max = 80; final int random = new Random().nextInt((max - min) + 1) + min; 
like image 167
Phantômaxx Avatar answered Oct 25 '22 19:10

Phantômaxx


Random r = new Random(); int i1 = r.nextInt(45 - 28) + 28; 

This gives a random integer between 28 (inclusive) and 45 (exclusive), one of 28,29,...,43,44.

like image 40
Narendra Sorathiya Avatar answered Oct 25 '22 17:10

Narendra Sorathiya