获得两个值范围内的随机长

getting a random long in range of two values

我写了一个简单的自动点击脚本,它工作正常,每次我相信它应该点击它。不过,我想知道的一件事是,它会以 2500 毫秒到 5000 毫秒之间的随机间隔延迟。我只是不是 100% 是这样做的?

所有代码都在这里:

public static void click(int desiredAmount)
    {
        int counter = 0;
        Random rand = new Random();

        while (counter < desiredAmount)
        {
            try {
                Thread.sleep(rand.nextInt(5000-2500) + 2500);
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }

            robot.mousePress(MouseEvent.BUTTON1_DOWN_MASK);
            robot.mouseRelease(MouseEvent.BUTTON1_DOWN_MASK);
            ++counter;
        }
    }

只是一个简单的点击方法,我对这行代码感到担忧 Thread.sleep(rand.nextInt(5000-2500) + 2500);

我正在使用 nextInt(int x) 方法获取两个值之间的随机 INT,但我使用的 Thread.sleep(); 方法将 long 作为参数。这是否意味着它会被截断或什么的?不是 2500 毫秒而是 2 秒?或 3 秒或 4 秒而不是 2646 毫秒或 3876 毫秒等?

它实际上是将每次点击延迟 2500-5000 毫秒吗?我很难弄明白。

延迟值将是一个从 2500 到 4999 的随机数,因为 nextInt 上限是唯一的。来自 Java SE Specification:

public int nextInt(int bound)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability.

rand.nextInt(5000-2500) + 2500rand.nextInt(2500) + 2500 相同(我认为这是一种更简洁的写法)。

此外,int 值被转换为 long 而不会丢失信息(long 的范围比 int 大,所以没有问题)。来自 Java SE Specification:

A conversion from type int to type long requires run-time sign-extension of a 32-bit integer value to the 64-bit long representation. No information is lost.

最后关于随机不是真正的随机,你是对的它是pseudo-random(这意味着所有可能的数字都没有完全相等的概率,而是近似相等的概率)。我不完全确定您将此代码用于什么目的,但我认为这将“足够随机”地满足您的需求。

您可以查看 this post 给定范围内 java 中的随机值。 this post 关于 Random 随机性。

PD: 您的代码(恕我直言)的一个很好的改进是使 rand 变量 private static 而不是 local.