我想用 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 文档 说,此方法调用返回0(包含)和指定值(不包含)之间的伪随机、均匀分布的 int 值".这意味着在您的情况下,您将获得从 0 到 9 的数字.因此,通过在该数字上加 1,您已正确完成所有操作.
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 之间的随机数
发布评论