使用 iOS,我有时喜欢在按下按钮时随机调用 2 个函数,例如,我会使用;因此有时,用户会得到 (1),其他时间会得到 (2) 等等。
if (arc4random() % 2 == 0) {
// Do one thing (1)
} else {
// Do something else(2)
}
}
我如何在 Eclipse/java 中执行此操作?换句话说,相同的语句在 Java 语言中是什么?
最佳答案
使用 Java Random 类。这将为您提供 1 或 2:
Random rand = new Random();
int n = rand.nextInt(2) + 1;
nextInt(n) 为您提供 0 到 n-1(含)之间的随机数。所以你必须给结果加 1。
关于java - arc4random 相当于 Java 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24252999/