随机元素生成而不重复Java

随机元素生成而不重复Java

本文介绍了随机元素生成而不重复Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让这段代码运行没有重复,但没有成功研究这一领域。

I am trying to get this code to run without duplicates but am having no success researching this area.

它是我正在做的一个问题的开始,将要求用户输入缺少的元素。但是,当我生成随机元素时,我会得到重复的值。

Its the start of a question I am doing which will ask the user to input the missing element. However, when I generate random elements I am getting duplicates

import java.util.Random;

public class QuestionOneA2 {

    public static void main(String[] args) {

        String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"};
        Random numberGenerator = new Random();

        for (int i = 0; i < 5; i++) {
            int nextRandom = numberGenerator.nextInt(6);
            System.out.println(fruit[nextRandom]);
        }


    }

}


推荐答案

您可以使用 Set 来验证随机生成的数字是否重复。您只需要继续生成 randomNumber ,直到找到一个唯一的随机值,然后将其添加到 Set 以防止重复

You can use a Set to validate if the random generated number is duplicate or not. You just have to keep generating randomNumber until you find a unique random and then add it to the Set to prevent the duplicates.

这是一个快速的代码片段:

Here is a quick code snippet:

public static void main(String[] args) {
    String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"};
        Random numberGenerator = new Random();
        /* Generate A Random Number */
        int nextRandom = numberGenerator.nextInt(6);
        Set<Integer> validate = new HashSet<>();
        /* Add First Randomly Genrated Number To Set */
        validate.add(nextRandom);
        for (int i = 0; i < 5; i++) {
            /* Generate Randoms Till You Find A Unique Random Number */
            while(validate.contains(nextRandom)) {
                nextRandom = numberGenerator.nextInt(6);
            }
            /* Add Newly Found Random Number To Validate */
            validate.add(nextRandom);
            System.out.println(fruit[nextRandom]);
        }
}

输出:

mango
apple
strawberry
pear
orange

这篇关于随机元素生成而不重复Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:41