如何在Java中随机播放数组?
声明一个字符串数组并以字母形式添加元素-
String[] letters = { "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" };将上面的数组转换为列表-
List<String>list = Arrays.asList(letters);
现在,使用Random类对象创建一个随机播放的数组,并使用nextInt()-生成随机字母
int len = list.size();
System.out.println("Shuffled array...");
for (int i = 0; i < letters.length; i++) {
int index = new Random().nextInt(len);
String shuffle = list.get(index);
System.out.println(shuffle);
}示例
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class Demo {
public static void main(String[] args) {
String[] letters = { "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" };
System.out.println("Initial array = "+Arrays.toString(letters));
List<String>list = Arrays.asList(letters);
int len = list.size();
System.out.println("Shuffled array...");
for (int i = 0; i < letters.length; i++) {
int index = new Random().nextInt(len);
String shuffle = list.get(index);
System.out.println(shuffle);
}
}
}输出结果
Initial array = [P, Q, R, S, T, U, V, W, X, Y, Z] Shuffled array... P X S X W S V R Y Q R
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短