Mike Rueda Mike Rueda - 1 year ago 78
Java Question

How to pick more than one string from arraylist randomly?

Hi i am trying to choose more than one string randomly from this list of arrays

import java.util.Random;
public class RandomSelect {

public static void main (String [] args) {

String [] arr = {"A", "B", "C", "D"};
Random random = new Random();

// randomly selects an index from the arr
int select = random.nextInt(arr.length);

// prints out the value at the randomly selected index
System.out.println("Random String selected: " + arr[select]);


Answer Source

To select two or more strings randomly from an array I would use a for loop and two generated integers. One random integer to select an element in the string array, and the other to determine how many times the for loop runs.

String [] arr = {"A", "B", "C", "D"}; Random random = new Random();

int n = random.nextInt(arr.length - 2 + 1) + 2;

for(int i = 0; i < n; n++){ int e = random.nextInt(arr.length); System.out.println("Random String selected: " + arr[e]); }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download