Skip to content

Instantly share code, notes, and snippets.

@rmg007
Created October 21, 2022 11:59
Show Gist options
  • Save rmg007/4cb71a2d5253f5eda8aac4520bb28be3 to your computer and use it in GitHub Desktop.
Save rmg007/4cb71a2d5253f5eda8aac4520bb28be3 to your computer and use it in GitHub Desktop.
Generate Random Numbers in Java
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class RandomNumbers {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(getRandomNumber_4(4, 9));
}
}
static int getRandomNumber_1(int min, int max){
Random random = new Random();
int range = max - min;
return random.nextInt(range) + min;
}
static int getRandomNumber_2(int min, int max){
Random random = new Random();
return random.ints(min, max)
.findFirst()
.orElse(0);
}
static int getRandomNumber_3(int min, int max){
int range = max - min;
int rand = (int)(Math.random() * range) + min;
return rand;
}
static int getRandomNumber_4(int min, int max){
return ThreadLocalRandom
.current()
.nextInt(min, max);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment