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.
Solution 1:
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;
Solution 2:
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.
Solution 3:
Also, from API level 21 this is possible:
int random = ThreadLocalRandom.current().nextInt(min, max);
Solution 4:
/**
* min and max are to be understood inclusively
*/
public static int getRandomNumber(int min, int max) {
return (new Random()).nextInt((max - min) + 1) + min;
}
Solution 5:
" the user is the one who select max no and min no ?" What do you mean by this line ?
You can use java function int random = Random.nextInt(n)
. This returns a random int in range[0, n-1]).
and you can set it in your textview using the setText()
method