我想知道如何获得 Integer.MIN_VALUE 和 Integer.MAX_VALUE 之间的随机整数。我确实尝试过:
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
Random rand = new Random();
StartVärde = rand.nextInt(max - min + 1) + min;
请注意,我已经导入了 java.util.Random,“StartVärde”只是我创建的一个变量。现在上面的代码给出了以下错误消息:
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:265)
at Räknare.<init>(Räknare.java:28)
at Räknare_Main.main(Räknare_Main.java:5)
最佳答案
来自 Random.nextInt()
的 javadoc
Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 232 possible int values are produced with (approximately) equal probability.
因此,如果您使用 Random.nextInt()
将返回一个介于 Integer.MIN_VALUE
和 Integer.MAX_VALUE
之间的值
关于java - 随机整数 - 正数和负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886455/