简体   繁体   中英

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.

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

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM