如何在 android 中打乱数组的字母?
how to shuffle a letters of array in android?
String arrAnimal[] = {"cat","dog","parrot","fish"};
我需要打乱每个单词并将其设置为 TextView,当单击按钮想要遍历每个元素时(请参阅随机排列的元素)。
使用Collections.shuffle( )
ArrayList<String> list = new ArrayList<String>();
list.add("cat");
list.add("dog");
list.add("parrot");
list.add("fish");
Collections.shuffle(list);
完整的工作代码,
String[] animals = {"cat","dog","parrot","fish"};
for (int i = 0; i < animals.length; ++i) {
List<Character> letters = new ArrayList<>(animals[i].length());
for (char c : animals[i].toCharArray()) {
letters.add(c);
}
Collections.shuffle(letters);
StringBuilder builder = new StringBuilder();
for (char c : letters) {
builder.append(c);
}
animals[i] = builder.toString();
}
System.out.println(Arrays.toString(animals));
输出:[tca, ogd, roptar, sifh]
编辑:要逐行打印,请将最后一行更改为,
for (String s : animals) {
System.out.println(s);
}
String arrAnimal[] = {"cat","dog","parrot","fish"};
我需要打乱每个单词并将其设置为 TextView,当单击按钮想要遍历每个元素时(请参阅随机排列的元素)。
使用Collections.shuffle( )
ArrayList<String> list = new ArrayList<String>();
list.add("cat");
list.add("dog");
list.add("parrot");
list.add("fish");
Collections.shuffle(list);
完整的工作代码,
String[] animals = {"cat","dog","parrot","fish"};
for (int i = 0; i < animals.length; ++i) {
List<Character> letters = new ArrayList<>(animals[i].length());
for (char c : animals[i].toCharArray()) {
letters.add(c);
}
Collections.shuffle(letters);
StringBuilder builder = new StringBuilder();
for (char c : letters) {
builder.append(c);
}
animals[i] = builder.toString();
}
System.out.println(Arrays.toString(animals));
输出:[tca, ogd, roptar, sifh]
编辑:要逐行打印,请将最后一行更改为,
for (String s : animals) {
System.out.println(s);
}