声明一个字符串数组并以字母形式添加元素-
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