+ 1

# Random integer in java

How do you get a random integer in a range in java? e.g. a random integer between 5-10

4 Answers

0

System.out.println((int)(Math.random()*5+5));

+ 11

According to :
https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java
The standard way to do it in Java 1.7 or later is:
import java.util.concurrent.ThreadLocalRandom;
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

+ 3

Solution-1:
public static int randInt(int min, int max) {
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Solution-2:
randomNum = minimum + (int)(Math.random() * (maximum - minimum));