How can I generate a random number in a certain ra

2019-01-14 15:43发布

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.

8条回答
Animai°情兽
2楼-- · 2019-01-14 15:52
private int getRandomNumber(int min,int max) {
    return (new Random()).nextInt((max - min) + 1) + min;
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-14 15:57

So you would want the following:

int random;
int max;
int min;

...somewhere in your code put the method to get the min and max from the user when they click submit and then use them in the following line of code:

random = Random.nextInt(max-min+1)+min;

This will set random to a random number between the user selected min and max. Then you will do:

TextView.setText(random.toString());
查看更多
小情绪 Triste *
4楼-- · 2019-01-14 15:59

You can use If Random. For example, this generates a random number between 75 to 100.

final int random = new Random().nextInt(26) + 75;
查看更多
祖国的老花朵
5楼-- · 2019-01-14 16:02

Also, from API level 21 this is possible:

int random = ThreadLocalRandom.current().nextInt(min, max);
查看更多
欢心
6楼-- · 2019-01-14 16:03
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.

查看更多
爷的心禁止访问
7楼-- · 2019-01-14 16:10

To extend what Rahul Gupta said:

You can use the 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;
查看更多
登录 后发表回答