Is it possible to generate random no. from the given set of no. like 5, 50, 20? If so please give simple example thanks.
Asked
Active
Viewed 3,977 times
1
-
Of course it is possible. Build an array. `int[] vals = {5, 50, 20};` - pick a random value from that array. Repeat as necessary. – Elliott Frisch May 21 '18 at 21:04
3 Answers
4
public class RandomNumbers {
public static void main(String[] args) {
int[] randomNumbers = new int[] { 2, 3, 5, 7, 11, 13, 17, 19 };
Random r = new Random();
int nextRandomNumberIndex = r.nextInt(randomNumbers.length);
System.out.println(randomNumbers[nextRandomNumberIndex]);
}
}

LuCio
- 5,055
- 2
- 18
- 34
3
You can use Random.nextInt()
to get a random index
.
Use that index
to get you pseudo random element:
int[] arr = {1, 2, 3};
int randomIndex = Random.nextInt(arr.length);
int randomVal = arr[randomIndex];

Mạnh Quyết Nguyễn
- 17,677
- 1
- 23
- 51
2
Here's one way to do it.
import java.util.concurrent.ThreadLocalRandom;
class randomFromList {
public static void main(String[] args) {
int x = 0;
int[] arr = {5, 50, 20}; // any set of numbers of any length
for (int i = 0; i < 100; i++) { // prints out 100 random numbers from the list
x = ThreadLocalRandom.current().nextInt(0, arr.length); // random number
System.out.println(arr[x]); // item at random index
}
}
}
It is better to use java.util.concurrent.ThreadLocalRandom as of Java 1.7+. See here for why. However, if you're using a version that predates Java 1.7, use Random

meyi
- 7,574
- 1
- 15
- 28