-2

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]); 
    }
}
Michael Lihs
  • 7,460
  • 17
  • 52
  • 85
  • 2
    Use a loop? How many times do you want to pick a random element? – Elliott Frisch Oct 29 '16 at 00:14
  • Possible duplicate of [Take n random elements from a List?](http://stackoverflow.com/questions/4702036/take-n-random-elements-from-a-liste) – Joe Oct 29 '16 at 12:53

3 Answers3

1

To select two or more strings randomly from an array, I would use a for loop in combination with 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, selecting an element for each time it loops.

String [] arr = {"A", "B", "C", "D"};

Random random = new Random();
int n = 0;
int e = 0;

//A random integer that is greater than 1 but not larger than arr.length
n = random.nextInt(arr.length - 2 + 1) + 2;

//loops n times selecting a random element from arr each time it does
for(int i = 0; i < n; n++){
   e = random.nextInt(arr.length);
   System.out.println("Random String selected: " + arr[e]);
}
Todd
  • 758
  • 1
  • 9
  • 20
0

If I understood you correctly, then I think you can just run

// 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]); 

again. It will select another random String from the array and print it out.

Kröw
  • 504
  • 2
  • 13
  • 31
0

If you want peek data at random order but do not peek same element twice, you can just randomly reorder your data and then process it in usual loop

List<String> data = Arrays.asList("A", "B", "C");
Collections.shuffle(data)
for (String item: data) {
    ...
}
rustot
  • 331
  • 1
  • 11