Java Random Array Access: Get Random Values

To randomly retrieve values from an array, you can use the java.util.Random class to generate a random number, and then use that random number as an index to retrieve values from the array.

Here is a sample code:

import java.util.Random;

public class RandomArrayValue {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        
        Random random = new Random();
        int index = random.nextInt(array.length); // 生成一个0到数组长度-1的随机数作为索引
        
        int randomValue = array[index]; // 获取数组中随机索引位置的值
        
        System.out.println("随机获取的值为: " + randomValue);
    }
}

In the example above, an array containing integers is first created, then a random index is generated using the Random class, and finally a random value from the array is retrieved using that random index.

bannerAds