【问题标题】:How to randomly change value of string array?如何随机更改字符串数组的值?
【发布时间】:2019-07-11 19:46:18
【问题描述】:

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

这是数组:

people = new ArrayList<>();

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

"text" 是我的文本视图,"people" 是我的数组,有 4 个值。我试过这个:

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

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

KimKimKimKim

【问题讨论】:

  • 那是因为rando 除了在循环外部获得的值之外,永远不会得到不同的值。并且即使它被设置在 inside 循环中(应该如此),您很可能会得到一些重复的值。最终,全部

标签: android arrays random


【解决方案1】:

您可以使用Collections.shuffle(people); 从arraylist 中获取改组后的名称。一行代码应该可以满足您的需求

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      你可以试试这个方法

      public static String getRandom(String[] people) {
         int rnd = new Random().nextInt(people.length);
         return people[rnd];
      }
      

      【讨论】:

        猜你喜欢
        • 2014-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多