为什么 int answer = generator.nextInt(10) + 1;只产生 1 到 10 之间的数字?
Why does int answer = generator.nextInt(10) + 1; only produce numbers between 1 and 10?
我不明白为什么它不能生成 11 以上的值。
这是我的测试代码:
import java.util.Random;
public class randomNumberTest
{
public static void main(String[] args)
{
Random rn = new Random();
//tests random number generator (between 1(inc) and 10(excl))
for(int i =0; i < 100; i++)
{
int answer = rn.nextInt(10) + 1;
System.out.println(answer);
}
}
}
阅读 Javadoc。 rn.nextInt(10)
生成从 0 到 9 的数字。加 1 得到 1 到 10 的范围。
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
我不明白为什么它不能生成 11 以上的值。
这是我的测试代码:
import java.util.Random;
public class randomNumberTest
{
public static void main(String[] args)
{
Random rn = new Random();
//tests random number generator (between 1(inc) and 10(excl))
for(int i =0; i < 100; i++)
{
int answer = rn.nextInt(10) + 1;
System.out.println(answer);
}
}
}
阅读 Javadoc。 rn.nextInt(10)
生成从 0 到 9 的数字。加 1 得到 1 到 10 的范围。
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)