如何在android中改组数组字母?

时间:2015-08-05 17:36:54

标签: android arrays string random shuffle

String arrAnimal[] = {"cat","dog","parrot","fish"};

我需要将每个单词洗牌并将其设置为TextView,当单击按钮想要遍历每个元素时(请参阅“受阻元素”)。

2 个答案:

答案 0 :(得分:0)

完整的工作代码,

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

答案 1 :(得分:-1)

使用Collections.shuffle()

obj = nullptr;