Java: Get a Random Item from an Array - Simple Guide
To get a random item from an array in Java, you can use the 'Random' class along with the 'nextInt' method. Here is an example:
import java.util.Random;
public class RandomItemFromArray {
public static void main(String[] args) {
String[] array = {'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'};
// Create a Random object
Random random = new Random();
// Generate a random index within the array length
int randomIndex = random.nextInt(array.length);
// Get the random item from the array using the generated index
String randomItem = array[randomIndex];
// Print the random item
System.out.println('Random item: ' + randomItem);
}
}
In this example, we have an array of strings 'array'. We create a 'Random' object called 'random'. Then, we use the 'nextInt' method of the 'random' object to generate a random index within the range of the array length. Finally, we retrieve the item at the random index from the array and store it in the 'randomItem' variable. The 'randomItem' is then printed to the console.
原文地址: https://www.cveoy.top/t/topic/qwT 著作权归作者所有。请勿转载和采集!