简体   繁体   中英

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?

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

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

So your nextInt call is

  1. taking the return value, which is in the range [0..bound] (where the bound is (max-min)+1 ) and then
  2. scaling it into the range [min..max] with +min .
return r.nextInt((max-min)+1)+min;
       \__________1_________/\_2_/

nextInt is normally exclusive of the top value, so add 1 to make it inclusive

So, in your case, we'll say the max is 10 and min is 5.

nextInt(n) will give you a random number between 0 and n - 1.

So adding the +1 will let you include the value of 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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