gpt4 book ai didi

java - hashset从数组Java中删除重复项

转载 作者:行者123 更新时间:2023-12-02 03:46:34 28 4
gpt4 key购买 nike

我目前正在尝试让我的java程序不在打印输出中打印出重复的法律。该软件是随机挑选打印出 1 到 3 个定律,但我不想要重复的。我对java还是个新手,到目前为止只写了几个程序。这是迄今为止我写过的最复杂的一篇。

现在,如果软件发现重复项,我希望软件再次运行随机项,直到打印中没有重复项为止。有办法做到这一点吗?

/**
*Seeds is a random number to pick which if statement will be used.
* telling the software how many laws to use during its random
* generation process
*
*/
Random seeds = new Random();
seed = seeds.nextInt(3) + 1;

if (seed == 1){


/**Beginning of random law selection for universe. Must find way
*Must find way to get rid of duplicate answers
*/
final String[] Laws = {"Standard Physics", "Magic", "Mad Science",
"Psionics", "Substandard Physics","Exotic"};
Random random = new Random();
int index = random.nextInt(Laws.length);
System.out.println("Law:" + Laws[index]);
}

else if (seed == 2) {

final String[] Laws = {"Standard Physics", "Magic", "Mad Science",
"Psionics", "Substandard Physics","Exotic"};
Random random = new Random();
int index = random.nextInt(Laws.length);
int index2 = random.nextInt(Laws.length);
System.out.println("Law:" + Laws[index] + "," + Laws[index2]);

}

else {

final String[] Laws = {"Standard Physics", "Magic", "Mad Science",
"Psionics", "Substandard Physics","Exotic"};
Random random = new Random();
int index = random.nextInt(Laws.length);
int index2 = random.nextInt(Laws.length);
int index3 = random.nextInt(Laws.length);
System.out.println("Law: " + Laws[index] + "," + Laws[index2] +
"," + Laws[index3]);

}

最佳答案

思考这个问题的另一种方式是;您想以随机顺序选择值。这样,除非元素出现多次,否则您不会获得重复项。

List<String> laws = Arrays.asList("Standard Physics", "Magic", "Mad Science", 
"Psionics", "Substandard Physics","Exotic");
Collections.shuffle(laws);
// select as many as you need
List<String> lawsSelected = laws.subList(0, 3);

关于java - hashset从数组Java中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36245821/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com