How to get a random integer in java?

java

Solution

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

Problem

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!

Original source

Related problems