gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:07 25 4
gpt4 key购买 nike

我写了一个简单的自动点击脚本,它工作正常,因为每次我相信它应该点击它。不过,我想知道的一件事是,它会以 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.

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

你可以看看this post关于给定范围之间java中的随机值。和 this post关于随机性。

PD:您的代码(恕我直言)的一个很好的改进是使 rand 变量成为 private static 而不是本地变量。

关于java - 获得两个值范围内的随机长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34712280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com