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

How Can I Randomly Pick an Element from an Integer Array in Java?

Susan Sarandon
Release: 2024-12-05 15:08:10
Original
609 people have browsed it

How Can I Randomly Pick an Element from an Integer Array in Java?

Picking Elements Randomly from an Array

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?

Solution

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template