how to select a random element from an array in java

htt‮/:sp‬/www.lautturi.com
how to select a random element from an array in java

To select a random element from an array in Java, you can use the Math.random() method and the length property of the array.

Here is an example of how you can do this:

int[] array = {1, 2, 3, 4, 5};

int index = (int) (Math.random() * array.length);

int randomElement = array[index];

The Math.random() method returns a random value between 0 (inclusive) and 1 (exclusive). By multiplying this value by the length of the array, we get a random number between 0 (inclusive) and the length of the array (exclusive). We then cast this value to an int and use it as the index to select a random element from the array.

Created Time:2017-11-01 20:43:00  Author:lautturi