我想在Java中生成1到10之间的数字。
I want to generate a number between 1 and 10 in Java.
这是我尝试过的:
Random rn = new Random(); int answer = rn.nextInt(10) + 1;有没有办法告诉括号中的内容()调用nextInt方法时要添加什么?
Is there a way to tell what to put in the parenthesis () when calling the nextInt method and what to add?
推荐答案as 文档说,此方法调用返回伪随机,均匀分布的int值介于0(包括)和指定值(不包括)之间。这意味着在您的情况下,您将获得0到9之间的数字。所以你已经通过在该数字上加一个来正确地完成了所有事情。
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
一般来说,如果你需要从 min 到 max (包括两者),你写的
Generally speaking, if you need to generate numbers from min to max (including both), you write
random.nextInt(max - min + 1) + min更多推荐
生成1到10个Java之间的随机数
发布评论