2
int totalRecs = getTotalRecs(); // returns '13'
int MAX_RECS_PER_LOOKUP = 10;
Random rand = new Random();
int start = (totalRecs > Utl.MAX_RECS_PER_LOOKUP) ? rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP) : 0;
results = this.getNewRecs(filter, start, start+1);

I'm using this random number logic to retrieve records from the database based on their table row offset (start up to start+1).

But for some reason it keeps repeating the same numbers: start value of 0 and start value of 3.

I tried seeding the Random object but it made no difference:

long seed = System.currentTimeMillis();
rand.setSeed(seed);
2
  • What is Utl.MAX_RECS_PER_LOOKUP? Likely the issue isn't rand.nextInt but rather your inputs are constraining it to a tiny subset of possible ints. Commented Nov 11, 2010 at 13:39
  • 2
    Something very odd happening. If totalRecs is really 13 then you shouldn't be getting 3 (as you're passing 3 to nextInt and that is the exclusive upper limit). Can you try printing the value of totalRecs and check it's what you think? Why are you using Utl.MAX_RECS_PER_LOOKUP rather than the MAX)RECS_PER_LOOKUP you just set? Commented Nov 11, 2010 at 13:39

3 Answers 3

3

The rand.nextInt(n) method returns a value between 0 (inclusive) and n (exclusive).

In your code, if totalRecs is 13, and Utl.MAX_RECS_PER_LOOKUP is 10 (I am assuming this one based on the MAX_RECS_PER_LOOKUP value in your code snippet, but I may be wrong), then this code:

rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP);

should return a random number between 0 and 2.

I am not sure if this is what you actually want?

Sign up to request clarification or add additional context in comments.

Comments

0

Make sure your inputs are valid.

Via debug compare values of

totalRecs Utl.MAX_RECS_PER_LOOKUP & start on the same iteration.

You are calling

rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP)

The only way you should "always" be getting 0 is if totalRecs = Utl.MAX_RECS_PER_LOOKUP However if the difference is only 1 then you will get back 0 or 1 randomly.

Comments

-1

You could try java.security.SecureRandom

It seems to be a good alternative, and it inherits from java.util.Random

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.