【问题标题】:Picking a random item from an array of strings in java [duplicate]从java中的字符串数组中选择一个随机项[重复]
【发布时间】:2026-02-16 05:10:01
【问题描述】:

我有一些包含字符串的数组,我想从每个数组中随机选择一个项目。我怎样才能做到这一点?

这是我的数组:

static final String[] conjunction = {"and", "or", "but", "because"};

static final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"};

static final String[] common_noun = {"man", "woman", "fish", "elephant", "unicorn"};

static final String[] determiner = {"a", "the", "every", "some"};

static final String[] adjective = {"big", "tiny", "pretty", "bald"};

static final String[] intransitive_verb = {"runs", "jumps", "talks", "sleeps"};

static final String[] transitive_verb = {"loves", "hates", "sees", "knows", "looks for", "finds"};

【问题讨论】:

标签: java arrays random


【解决方案1】:

使用Random.nextInt(int) 方法:

final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"};
Random random = new Random();
int index = random.nextInt(proper_noun.length);
System.out.println(proper_noun[index]);

这段代码并不完全安全:四分之二的时候它会选择 Richard Nixon。

引用文档Random.nextInt(int)

返回一个伪随机的、在 0 之间均匀分布的 int 值 (含)和指定值(不含)

在您的情况下,将数组长度传递给 nextInt 即可解决问题 - 您将获得 [0; your_array.length) 范围内的随机数组索引

【讨论】:

    【解决方案2】:

    如果您使用 List 而不是数组,您可以创建简单的通用方法,从任何列表中获取随机元素:

    public static <T> T getRandom(List<T> list)
    {
    Random random = new Random();
    return list.get(random.nextInt(list.size()));
    }
    

    如果你想继续使用数组,你仍然可以使用你的泛型方法,但它看起来会有点不同

    public static <T> T   getRandom(T[] list)
    {
        Random random = new Random();
        return list[random.nextInt(list.length)];
    
    }
    

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        如果你想循环遍历你的数组,你应该把它们放入一个数组中。否则,您需要分别为每一个进行随机选择。

        // I will use a list for the example
        List<String[]> arrayList = new ArrayList<>();
        arrayList.add(conjunction);
        arrayList.add(proper_noun);
        arrayList.add(common_noun);
        // and so on..
        
        // then for each of the arrays do something (pick a random element from it)
        Random random = new Random();
        for(Array[] currentArray : arrayList){
            String chosenString = currentArray[random.nextInt(currentArray.lenght)];
            System.out.println(chosenString);
        }
        

        【讨论】: