如何随机更改字符串数组的值?

问题描述 投票:0回答:3

我已经创建了一个带有一些名称的字符串数组,现在我想更改值的顺序,然后使用for循环。我唯一的问题是我不知道如何更改数组值顺序。这是我的代码:

This is the array:

people = new ArrayList<>();

people.add("Sam");
people.add("John");
people.add("Kim");
people.add("Edison");

“text”是我的textview,“people”是我的数组,有4个值。我试过这个:

int rando = (int)(Math.random() *4);
for (i=0; i< people.size(); i++) {
text.append(people.get(rando));
}

但它只打印四次其中一个值。像这样:

KimKimKimKim

android arrays random
3个回答
1
投票

您可以使用Collections.shuffle(people);从arraylist中获取随机播放的名称。一行代码应该是您正在寻找的技巧

textView.setText(TextUtil.join(",", Collections.shuffle(people));

0
投票

试试这个。这就是我在我的音乐播放器应用程序中播放歌曲的方式

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

0
投票

你可以尝试这种方法

public static String getRandom(String[] people) {
   int rnd = new Random().nextInt(people.length);
   return people[rnd];
}
© www.soinside.com 2019 - 2024. All rights reserved.