简体   繁体   English

我想在java中给定范围内生成随机数

[英]I want to generate random numbers within given range in java

For that, I got the solution but I can't understand it: I have used below function to generate random numbers within the given range but what is the meaning of below function? 为此,我得到了解决方案,但我不明白:我使用了below函数来生成给定范围内的随机数,但是below函数的含义是什么?

static int randomRangeInNumber(int min, int max) {
    Random r=new Random();
    return r.nextInt((max-min)+1)+min;
}

What i have returned i didnt get Please help making me understand its meaning any help will be appreciated 我没有得到的退货请帮助我理解其含义,将不胜感激

The documentation for nextInt(int bound) says 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. 返回一个伪随机数,它从此随机数生成器的序列中提取,在0(含)和指定值(不含)之间均匀分布的int值。

So your nextInt call is 所以你的nextInt电话是

  1. taking the return value, which is in the range [0..bound] (where the bound is (max-min)+1 ) and then 取返回值,范围为[0..bound](界限为(max-min)+1 ),然后
  2. scaling it into the range [min..max] with +min . +min将其缩放到[min..max]范围。
return r.nextInt((max-min)+1)+min;
       \__________1_________/\_2_/

nextInt is normally exclusive of the top value, so add 1 to make it inclusive nextInt通常不包含最高值,因此加1使其包含在内

So, in your case, we'll say the max is 10 and min is 5. 因此,在您的情况下,我们说max为10, min为5。

nextInt(n) will give you a random number between 0 and n - 1. nextInt(n)将为您提供0到n-1之间的随机数。

So adding the +1 will let you include the value of n . 因此,加上+1将使您包括n的值。

nextInt(max-min) therefore gives you a random number between (in this case) 0 and 5 - 1 (and include the 5 because of the +1) nextInt(max-min)为您提供一个在0和nextInt(max-min)之间的随机数(在这种情况下,由于+1而包括了5)

Then adding the min again, means it will give you the above random number, but add 5 to it, so the result will be a random number between 5 and 10. 然后再次加上min ,表示它将为您提供上述随机数,但将其加5,因此结果将是5到10之间的随机数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM