How do I generate random integers within a specific range in Java? -
i trying generate random int
value java, in specific range.
for example:
my range 5-10, meaning 5 smallest possible value , 10 biggest. other number in between these numbers possible value, too.
in java, there method random()
in math
class, returns double
value between 0.0 , 1.0. in class random
there method nextint(int n)
, returns random int
value in range of 0 (inclusive) , n (exclusive). couldn't find method, returns random integer value between 2 numbers.
i have tried following things, still have problems: (minimum , maximum smallest , biggest numbers).
solution 1:
randomnum = minimum + (int)(math.random() * maximum);
problem:
randomnum
can bigger maximum
.
solution 2:
random rn = new random(); int n = maximum - minimum + 1; int = rn.nextint() % n; randomnum = minimum + i;
problem:
randomnum
can smaller minimum
.
how solve these problems?
i have tried browsing through archive , found:
but couldn't solve problem.
in java 1.7 or later, standard way follows:
import java.util.concurrent.threadlocalrandom; // nextint exclusive of top value, // add 1 make inclusive int randomnum = threadlocalrandom.current().nextint(min, max + 1);
see the relevant javadoc. approach has advantage of not needing explicitly initialize java.util.random instance, can source of confusion , error if used inappropriately.
however, conversely there no way explicitly set seed can difficult reproduce results in situations useful such testing or saving game states or similar. in situations, pre-java 1.7 technique shown below can used.
before java 1.7, standard way follows:
import java.util.random; /** * returns pseudo-random number between min , max, inclusive. * difference between min , max can @ * <code>integer.max_value - 1</code>. * * @param min minimum value * @param max maximum value. must greater min. * @return integer between min , max, inclusive. * @see java.util.random#nextint(int) */ public static int randint(int min, int max) { // note: (intentionally) not run written folks // copy-pasting have think how initialize // random instance. initialization of random instance outside // main scope of question, decent options have // field initialized once , re-used needed or // use threadlocalrandom (if using @ least java 1.7). random rand; // nextint exclusive of top value, // add 1 make inclusive int randomnum = rand.nextint((max - min) + 1) + min; return randomnum; }
see the relevant javadoc. in practice, java.util.random class preferable java.lang.math.random().
in particular, there no need reinvent random integer generation wheel when there straightforward api within standard library accomplish task.
Comments
Post a Comment