生成1到10个Java之间的随机数 [英] Generating a Random Number between 1 and 10 Java
问题描述
我想在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 $ c生成数字$ c>到
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之间的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!