Randomly selecting an element from an array is a common operation in programming. Suppose you have an integer array new int[]{1,2,3} and want to choose a number at random. How can this be achieved?
One straightforward approach involves utilizing Java's Random class, which provides methods for generating random numbers. The following method takes an integer array as input and returns a randomly chosen element:
public static int getRandom(int[] array) { int rnd = new Random().nextInt(array.length); return array[rnd]; }
The Random().nextInt(array.length) line generates a random integer between 0 and array.length - 1, inclusive. This ensures that the returned index will always fall within the range of valid indices for the array.
Usage:
int[] numbers = {1, 2, 3}; int randomNum = getRandom(numbers); System.out.println("Randomly selected number: " + randomNum);
This method effectively picks an element randomly from the input array and returns it.
The above is the detailed content of How Can I Randomly Pick an Element from an Integer Array in Java?. For more information, please follow other related articles on the PHP Chinese website!