0

I'm new at Java and trying to understand the concept of generating a random number within a specific range (of 500000 to 999999).

I wrote a function:

public int generateRandom(){

   Random random = new Random();
   return (int num = random.nextInt(900000) + 500000));

}

From what I get is that:

1. The + 500000 is the lowerbound so that the method will not generate any random number below that value, correct?

2. Will the upperbound of 900000 combined with lowerbound of + 500000 generate a max value of 1400000?

Because if random.nextInt(900000) returns a 900000 and then theres the + 500000 then it will all add up to 1400000 which will make my method not correct if I want to only generate numbers between 500000 to 999999?

James McTyre
  • 103
  • 7
  • Correct. You want to return `random.nextInt(upper - lower) + lower`. Or you can use `ThreadLocalRandom.nextInt(origin, bound)`. – shmosel Nov 13 '18 at 02:09
  • Correct. However, you also should avoid creating a new `Random` on every method invocation. That can impact results because in a loop the seed might not change. – Elliott Frisch Nov 13 '18 at 02:10

0 Answers0