我需要在 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()
最佳答案
Random rand = new Random();
int n = rand.nextInt(20); // Gives n such that 0 <= n < 20
文档:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. Thus, from this example, we'll have a number between 0 and 19
关于java - 使用 Android 时 Java 中的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6741100/