Picking a random element from an array is a common programming task. For instance, you may need to select a random name from a list or generate a random password.
Problem:
Given an integer array, how can we randomly select an element?
Solution:
We can use the Random class to generate a random number within the range of the array's length. This number is then used as an index to extract the random element.
import java.util.Random; public static int getRandom(int[] array) { int rnd = new Random().nextInt(array.length); return array[rnd]; }
For example, with the array new int[]{1,2,3}, the code would generate a random number between 0 and 2 (inclusive). If the random number is 1, the element at index 1 in the array will be returned, which is 2.
The above is the detailed content of How Can I Randomly Select an Element from an Integer Array?. For more information, please follow other related articles on the PHP Chinese website!