3

I'm trying to get a random integer, but the way I'm doing it takes a really long time to get that random number ( like 10 seconds!)

Random generator=new Random();
do {
    id=generator.nextInt();
}
while(id<=0||id>=4);

I'm trying to get a random number between (and include) 0 to 4 This code so far gets the job done, but 10 seconds is too long!

what is a better way to do this?

Thanks!

Salman Zaidi
  • 9,342
  • 12
  • 44
  • 61
ericDaWang
  • 182
  • 2
  • 6
  • 15

5 Answers5

10

You want

generator.nextInt(5);

which returns a random integer between 0 and 4. The reason why your original code took so long was because it was generating random integers over and over, until it got one between 1 and 3.

Note that as you were throwing away everything 0 or less, and everything 4 or more, you weren't even getting the range that you expected.

More information on the methods of the Random class can be found at http://docs.oracle.com/javase/7/docs/api/java/util/Random.html

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
1

That's because you're generating literally probably billions of random numbers and throwing them away until you get one between 0 and 4. Instead:

id = generator.nextInt(5); // number between 0 and 4, inclusive

In the future, please read the documentation for the classes you're using; this is clearly explained in the Javadoc.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
1

Use Math.random() cast it into int

int i=(int)Math.random()*4;
Nambi
  • 11,944
  • 3
  • 37
  • 49
0

Just include the upper bound (assuming you want 1, 2, or 3):

id = 1 + generator.nextInt(3);

From the javadoc:

public int nextInt(int n)

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

Vincent van der Weele
  • 12,927
  • 1
  • 33
  • 61
0

try this:

Random random = new Random();
random.nextInt(4);
A N M Bazlur Rahman
  • 2,280
  • 6
  • 38
  • 51