Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How can I generate a random number in a certain range? without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
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.
Answer
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;
We are here to answer your question about How can I generate a random number in a certain range? - If you find the proper solution, please don't forgot to share this with your team members.