Dipendra Ranamagar
Dipendra Ranamagar

Reputation: 37

To generate random numbers in java from given set of numbers

Is it possible to generate random no. from the given set of no. like 5, 50, 20? If so please give simple example thanks.

Upvotes: 1

Views: 4507

Answers (3)

meyi
meyi

Reputation: 8102

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

Upvotes: 2

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

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];

Upvotes: 3

LuCio
LuCio

Reputation: 5173

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]);
  }

}

Upvotes: 4

Related Questions