如何生成一定范围内的随机数? [英] How can I generate a random number in a certain range?

查看:489
本文介绍了如何生成一定范围内的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个应用程序,该应用程序使用Eclipse在Android中生成随机数,然后在TextView字段中显示结果?随机数必须在用户选择的范围内.因此,用户将输入范围的最大值和最小值,然后输出答案.

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.

推荐答案

扩展Rahul Gupta所说的话:

To extend what Rahul Gupta said:

您可以使用Java函数int random = Random.nextInt(n).
这将返回范围为[0, n-1]的随机int.

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

即,要获取范围[20, 80],请使用:

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

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

概括更多:

final int min = 20;
final int max = 80;
final int random = new Random().nextInt((max - min) + 1) + min;

这篇关于如何生成一定范围内的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆