我需要在1和20之间设置一个随机数,并根据这个数字(使用"If - Then“语句)来设置ImageView的图像。
我知道在Objective-C中,它是这样的:
int aNumber = arc4Random() % 20;
if (aNumber == 1) {
[theImageView setImage:theImage];
}
我如何在Java中做到这一点?我见过这样做,但我不知道如何设置数字的范围(1-20,2-7,等等)。
int aNumber = (int) Math.random()
发布于 2011-07-19 08:42:47
Docs are your friends
Random rand = new Random();
int n = rand.nextInt(20); // Gives n such that 0 <= n < 20
文档
返回一个伪随机的、均匀分布在0(包括)和指定值(不包括)之间的int值,该值是从这个随机数生成器的序列中提取的。因此,在本例中,我们将有一个介于0和19
之间的数字
发布于 2011-07-19 08:43:49
Math.random()
从[0,1[.Random.nextInt(int)
从[0,int
[.
发布于 2011-07-19 08:44:26
您可以尝试:
int aNumber = (int) (20 * Math.random()) + 1;
或
Random rand = new Random();
int n = rand.nextInt(20) + 1;
https://stackoverflow.com/questions/6741100
复制相似问题