如何在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
热门推荐
5 带清的简短祝福语
10 年前幸福祝福语大全简短
11 理科元旦祝福语大全简短
12 六一互换礼物祝福语简短
13 修祖屋祝福语简短
14 生日祝福语大全女孩简短
15 周末祝福语正能量简短
16 男朋友祝福语简短新年
17 冬至婆婆的祝福语简短
18 端午发给客户祝福语简短