在 Java 中创建随机数生成器 - 查看 num1 和 num2,在哪些情况下我会使用这些方法中的任何一种来创建 1 到 8 之间的随机数?一种比另一种更有效,还有其他好处吗?
import java.util.*;
public class Chpt3 {
public static void main(String[] args) {
Random rand = new Random();
int num1 = Math.abs(rand.nextInt()) % 8 + 1;
int num2 = rand.nextInt(8) + 1;
System.out.println(num1);
System.out.println(num2);
}
}
最佳答案
nextInt(n)
在 0
和 n-1
之间返回。
所以要在 1 到 8 之间,
int num2 = rand.nextInt(8) + 1;
这意味着您的第二个就是您需要的那个。
更新:
Math.abs(Integer.MIN_VALUE)
返回负值。
根据 this answer所以:
Integer.MIN_VALUE is -2147483648
, but the highest value a 32 bit integer can contain is+2147483647
. Attempting to represent+2147483648
in a 32 bit int will effectively "roll over" to-2147483648
. This is because, when using signed integers, the two's complement binary representations of+2147483648
and-2147483648
are identical. This is not a problem, however, as+2147483648
is considered out of range.For a little more reading on this matter, you might want to check out the Wikipedia article on Two's complement.
第一种方法只包含一个罕见的极端情况。这就是为什么最好使用第二个,因为它是安全的。
关于Java Math.abs 随机与 nextInt(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176165/