java - 使用 Android 时 Java 中的随机数

标签 java android integer

我需要在 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()

最佳答案

Docs are your friends

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/

相关文章:

java - 对 child 有限制的 hibernate 标准

java - EHCache刷新

java - 在Request Android Studio中做一个Toast

android - 如何在重定向到我的应用程序后关闭 Android 浏览器?

java - 有什么方法可以在不使用 ProGuard 优化的情况下删除日志记录调用?

c - 通过 TCP 发送一个整数(C 语言编程)

java - 应用程序崩溃 android Activity t40}}} 超时

c++ - (int)-2147483648 除以 (int)-1 的结果,使用不同的编译器?

c++ - 在数字中的特定数字处查找数字

java - unix 中字符串中双引号内的双引号