如何随机从arraylist中选择多个字符串?

时间:2016-10-29 00:13:27

标签: java

您好我想从这个数组列表中随机选择多个字符串

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

3 个答案:

答案 0 :(得分:1)

要从数组中随机选择两个或多个字符串,我会将for循环与两个生成的整数结合使用。一个随机整数,用于选择字符串数组中的元素,另一个用于确定for循环运行的次数,每次循环时选择一个元素。

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

答案 1 :(得分:0)

如果我理解正确,那么我认为你可以运行

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

一次。它将从数组中选择另一个随机字符串并将其打印出来。

答案 2 :(得分:0)

如果您希望以随机顺序查看窥视数据但不要同时查看相同的元素,则可以随机重新排序数据,然后在通常的循环中处理它

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