Home > Java > javaTutorial > How Can I Randomly Select an Element from an Integer Array?

How Can I Randomly Select an Element from an Integer Array?

DDD
Release: 2024-12-04 20:26:12
Original
437 people have browsed it

How Can I Randomly Select an Element from an Integer Array?

Randomly Picking an Element from an Array

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];
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template