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

Java 如何从arraylist中随机选取多个字符串?,java,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 fro

嗨,我正在尝试从数组列表中随机选择多个字符串

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

如果我没听错的话,我想你可以跑了

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

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

如果您希望以随机顺序查看数据,但不想查看同一元素两次,您可以随机重新排序数据,然后在常规循环中处理它

List<String> data = Arrays.asList("A", "B", "C");
Collections.shuffle(data)
for (String item: data) {
    ...
}
List data=Arrays.asList(“A”、“B”、“C”);
集合。洗牌(数据)
用于(字符串项:数据){
...
}

要从数组中随机选择两个或多个字符串,我将使用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]);
}
String[]arr={“A”、“B”、“C”、“D”};
随机=新随机();
int n=0;
int e=0;
//大于1但不大于arr.length的随机整数
n=随机。下一个(arr.length-2+1)+2;
//循环n次,每次从arr中选择一个随机元素
对于(int i=0;i
是否使用循环?您希望选取一个随机元素多少次?可能重复