如何在Android中 Shuffle 数组的字母?

hi3rlvi2  于 2023-03-06  发布在  Android
关注(0)|答案(3)|浏览(109)
String arrAnimal[] = {"cat","dog","parrot","fish"};

我需要 Shuffle 每个字,并将其设置为文本视图,当点击按钮要通过每个元素(见 Shuffle 元素)。

qlvxas9a

qlvxas9a1#

完整的工作代码,

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

v7pvogib2#

获取随机单词:

私有变量currentWord = getRandomWord()

存储数据的数组列表:

val dashboardList: List<String> =
    listOf("den",
        "music",
        "podcast",
        "library",
        "gallary",
        "work")

创建一个单独的方法从数组列表中获取随机单词:

private fun getRandomWord(): String {
        val word = allWordsList.random().toCharArray()
        word.shuffle()
        return String(word)
    }
0sgqnhkj

0sgqnhkj3#

使用集合.shuffle()

ArrayList<String> list = new ArrayList<String>();
list.add("cat");
list.add("dog");
list.add("parrot");
list.add("fish");

Collections.shuffle(list);

相关问题