+ 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

2nd Sep 2017, 12:23 PM
Robert Sokolov
Robert Sokolov - avatar
4 Respuestas
0
System.out.println((int)(Math.random()*5+5));
2nd Sep 2017, 12:50 PM
Devbrath
Devbrath - avatar
+ 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);
2nd Sep 2017, 12:48 PM
Hatsy Rei
Hatsy Rei - avatar
2nd Sep 2017, 12:48 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 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));
2nd Sep 2017, 12:50 PM
Mukund
Mukund - avatar