使用 Android 时 Java 中的随机数

2022-09-03 16:28:41

我需要创建一个介于 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()

答案 1

文档是您的朋友

Random rand = new Random();
int n = rand.nextInt(20); // Gives n such that 0 <= n < 20

文档

返回一个伪随机,均匀分布的 int 值,介于 0(包括 0)和指定值(不含)之间,该值取自此随机数生成器的序列。因此,从这个例子中,我们将有一个介于 0 和 19 之间的数字。


答案 2

Math.random()从 [0,1[. 返回一个 from [0, int[.doubleRandom.nextInt(int)int