如何在 Java 中生成 min 和 max 之间的随机整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2444019/
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 07:45:23  来源:igfitidea点击:

How do I generate a random integer between min and max in Java?

javarandom

提问by David

What method returns a random int between a min and max? Or does no such method exist?

什么方法返回最小值和最大值之间的随机整数?或者不存在这样的方法?

What I'm looking for is something like this:

我正在寻找的是这样的:

NAMEOFMETHOD (min, max) 

(where min and max are ints), that returns something like this:

(其中 min 和 max 是ints),返回如下内容:

8

(randomly)

(随机)

If such a method does exist could you please link to the relevant documentation with your answer.

如果确实存在这种方法,请您将答案链接到相关文档。

Thanks.

谢谢。



UPDATE

更新

Attempting to implement the full solution and I get the following error message:

尝试实施完整的解决方案,我收到以下错误消息:

class TestR
{
    public static void main (String[]arg) 
    {   
        Random random = new Random() ;
        int randomNumber = random.nextInt(5) + 2;
        System.out.println (randomNumber) ; 
    } 
} 

I'm still getting the same errors from the compiler:

我仍然从编译器收到相同的错误:

TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
        ^
TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
                            ^
TestR.java:6: operator + cannot be applied to Random.nextInt,int
        int randomNumber = random.nextInt(5) + 2;
                                         ^
TestR.java:6: incompatible types
found   : <nulltype>
required: int
        int randomNumber = random.nextInt(5) + 2;
                                             ^
4 errors


What's going wrong here?


这里出了什么问题?

采纳答案by Mark Byers

Construct a Random object at application startup:

在应用程序启动时构造一个 Random 对象:

Random random = new Random();

Then use Random.nextInt(int):

然后使用Random.nextInt(int)

int randomNumber = random.nextInt(max + 1 - min) + min;

Note that the both lower and upper limits are inclusive.

请注意,下限和上限均包括在内。

回答by MAK

You can use Random.nextInt(n). This returns a random int in [0,n). Just using max-min+1 in place of n and adding min to the answer will give a value in the desired range.

您可以使用Random.nextInt(n)。这将返回 [0,n) 中的随机整数。只需使用 max-min+1 代替 n 并将 min 添加到答案中就会给出所需范围内的值。

回答by darlinton

import java.util.Random;

导入 java.util.Random;

回答by julius.kabugu

This generates a random integer of size psize

这会生成一个大小为 psize 的随机整数

public static Integer getRandom(Integer pSize) {

    if(pSize<=0) {
        return null;
    }
    Double min_d = Math.pow(10, pSize.doubleValue()-1D);
    Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
    int min = min_d.intValue();
    int max = max_d.intValue();
    return RAND.nextInt(max-min) + min;
}

回答by Jupiter Kasparov

public static int random_int(int Min, int Max)
{
     return (int) (Math.random()*(Max-Min))+Min;
}

random_int(5, 9); // For example

回答by kerouac

Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :

按照已接受的答案中的建议,使用 Random 类是一种方法,但如果您不想创建新的 Random 对象,这里有一种不太直接的正确方法:

min + (int) (Math.random() * (max - min + 1));

回答by arcuri82

As the solutions above do not consider the possible overflow of doing max-minwhen minis negative, here another solution (similar to the one of kerouac)

由于上面的解决方案没有考虑 do max-minwhenmin为负的可能溢出,这里是另一种解决方案(类似于 kerouac 的解决方案)

public static int getRandom(int min, int max) {
    if (min > max) {
        throw new IllegalArgumentException("Min " + min + " greater than max " + max);
    }      
    return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}

this works even if you call it with:

即使您使用以下命令调用它,这也有效:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 

回答by palacsint

With Java 7 or above you could use

使用 Java 7 或更高版本,您可以使用

ThreadLocalRandom.current().nextInt(int origin, int bound)

Javadoc: ThreadLocalRandom.nextInt

Javadoc:ThreadLocalRandom.nextInt