【问题标题】:Get random strings from a list从列表中获取随机字符串
【发布时间】:2016-02-12 22:10:11
【问题描述】:

我有一个 ArrayList,它是在 main 方法之外定义的,就在 StringRandomize 类中:

 public static ArrayList<String> countries = new ArrayList<String>();

我还初始化了一个随机对象。

 Random obj = new Random();

然后我在列表中添加一些字符串:

    StringRandomize.countries.add("USA");
    StringRandomize.countries.add("GB");
    StringRandomize.countries.add("Germany");
    StringRandomize.countries.add("Austria");
    StringRandomize.countries.add("Romania");
    StringRandomize.countries.add("Moldova");
    StringRandomize.countries.add("Ukraine");

如何让这些字符串随机出现?我需要“德国”、“摩尔多瓦”等输出。
我需要输出中的字符串,而不是它们的 ID。 感谢您的帮助。

【问题讨论】:

  • countries.get(index)
  • "无法解析符号'index'"我做错了什么?
  • 如果您想打印所有内容(而不仅仅是获取随机元素),您还可以考虑使用Collections.shuffle 打乱列表。

标签: java arraylist random


【解决方案1】:

你可能想使用类似的东西:

countries.get(Math.abs(new Random().nextInt()) % countries.size());

或者,为了避免每次都创建一个新的 Random 对象,您可以使用相同的对象:

Random gen = new Random();
for (int i = 1; i < 10; i++) {
    System.out.println(countries.get(Math.abs(gen.nextInt()) % countries.size()));
}

【讨论】:

  • .nextInt(countries.size())
  • 我们可以这样做吗 countries.get(obj.nextInt()); ?
  • @AlexisC:确实如此。你也可以这样做。 @AmanKumar:可以,但要注意避免潜在的 indexOutOfBounds 异常。您必须确保 obj.nextInt() 为正且小于countries.size()
【解决方案2】:

如果你想要一个随机列表,我会使用 Collections.shuffle(countries)

其他 new Random().nextInt(max) 就像 Flavius 描述的那样。

【讨论】:

    【解决方案3】:
    static void shuffleArray(string[] ar)
      {
        //set the seed for the random variable
        Random rnd = ThreadLocalRandom.current();
        //go from the last element to the first one.
        for (int i = ar.size()- 1; i > 0; i--)
        {
          //get a random number till the current position and simply swap elements
          int index = rnd.nextInt(i + 1);
          // Simple swap
          int a = ar[index];
          ar[index] = ar[i];
          ar[i] = a;
        }
      }
    

    通过这种方式,您可以打乱整个数组并以随机顺序获取值,但根本不会重复。每一个元素都会改变位置,所以无论你选择什么元素(位置),你都会从一个随机位置获得一个国家。你可以返回整个向量,位置是随机的。

    【讨论】:

    • 你能评论一下吗?顺便说一句,我收到“无法解析方法'length()'”错误。
    猜你喜欢
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    相关资源
    最近更新 更多