我已经创建了一个带有一些名称的字符串数组,现在我想更改值的顺序,然后使用for循环。我唯一的问题是我不知道如何更改数组值顺序。这是我的代码:
people = new ArrayList<>();
people.add("Sam");
people.add("John");
people.add("Kim");
people.add("Edison");
int rando = (int)(Math.random() *4);
for (i=0; i< people.size(); i++) {
text.append(people.get(rando));
}
但它只打印四次其中一个值。像这样:
KimKimKimKim
您可以使用Collections.shuffle(people);
从arraylist中获取随机播放的名称。一行代码应该是您正在寻找的技巧
textView.setText(TextUtil.join(",", Collections.shuffle(people));
试试这个。这就是我在我的音乐播放器应用程序中播放歌曲的方式
for (i=0; i< people.size(); i++) {
shuffleText(people.size())
}
private void shuffleText(int size) {
int randomNumber = new Random().nextInt((size) + 1) + 1;
text.append(people.get(randomNumber));
}
你可以尝试这种方法
public static String getRandom(String[] people) {
int rnd = new Random().nextInt(people.length);
return people[rnd];
}