生成 1 到 10 Java 之间的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20389890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:36:38  来源:igfitidea点击:

Generating a Random Number between 1 and 10 Java

javarandom

提问by Shania

I want to generate a number between 1 and 10 in Java.

我想在 Java 中生成 1 到 10 之间的数字。

Here is what I tried:

这是我尝试过的:

Random rn = new Random();
int answer = rn.nextInt(10) + 1;

Is there a way to tell what to put in the parenthesis ()when calling the nextInt method and what to add?

有没有办法告诉()在调用 nextInt 方法时要在括号中放什么以及要添加什么?

采纳答案by Malcolm

As the documentationsays, 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.

正如文档所说,此方法调用返回“0(包含)和指定值(不包含)之间的伪随机、均匀分布的 int 值”。这意味着在您的情况下,您将获得从 0 到 9 的数字。因此,通过在该数字上加 1,您已正确完成所有操作。

Generally speaking, if you need to generate numbers from minto max(including both), you write

一般来说,如果你需要从minmax(包括两者)生成数字,你写

random.nextInt(max - min + 1) + min

回答by Scary Wombat

The standard way to do this is as follows:

执行此操作的标准方法如下:

Provide:

提供:

  • min Minimum value
  • max Maximum value
  • min 最小值
  • 最大值

and get in return a Integer between min and max, inclusive.

并返回一个介于最小值和最大值之间的整数,包括两者。

Random rand = new Random();

// nextInt as provided by Random is exclusive of the top value so you need to add 1 

int randomNum = rand.nextInt((max - min) + 1) + min;

See the relevant JavaDoc.

请参阅相关的JavaDoc

As explained by Aurund, Random objects created within a short time of each other will tend to produce similar output, so it would be a good idea to keep the created Random object as a field, rather than in a method.

正如 Aurund 所解释的那样,彼此在短时间内创建的 Random 对象往往会产生相似的输出,因此将创建的 Random 对象保留为一个字段而不是一个方法是一个好主意。

回答by Demosthanes

This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.

这将用于生成数字 1 - 10。确保在代码顶部导入 Random。

import java.util.Random;

If you want to test it out try something like this.

如果您想对其进行测试,请尝试这样的操作。

Random rn = new Random();

for(int i =0; i < 100; i++)
{
    int answer = rn.nextInt(10) + 1;
    System.out.println(answer);
}

Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).

此外,如果您更改括号中的数字,它将创建一个从 0 到该数字 -1 的随机数(除非您像这样添加一个,然后它将是从 1 到您输入的数字)。