连续生成随机枚举值,而不会两次获得相同的值 [英] Generating a random enum value continuously without getting the same value twice

查看:81
本文介绍了连续生成随机枚举值,而不会两次获得相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要随机分组的枚举团队。因此,我有:

I have a enum Teams that I want to randomise. So i have:

public enum Teams { TEAM1, TEAM2, TEAM3, TEAM4, TEAM5, TEAM6; }

然后我有了一个随机方法来随机生成值:

I then have a random method to generate the value randomly:

public static Teams getRandomTeam() {
    return Teams.values()[(int) (Math.random() * Teams.values().length)];
}

确实会返回随机生成的团队,但是我需要,一旦团队

Which does return a randomly generated team, however I need, once a team is generated, say TEAM2, it cannot be generated again.

我正在使用:

System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());

(我知道这是错误的,因为它一遍又一遍地调用该方法。

(which I know is wrong because it's calling the method over and over.

在我运行程序的那一刻,输出可能是:

At the minute when I run the program the out put could be:

团队是:TEAM2

团队是:TEAM2

团队是:TEAM4

团队是:TEAM2

团队是:TEAM3

团队是:TEAM2

但是我需要我的程序一次输出一次枚举值。
谢谢

But I need my program to output the an enum value once and once only. Thanks

推荐答案

只需使用 Collections.shuffle

List<Team> teams = new ArrayList<>();
Collections.addAll(teams, Team.values());
Collections.shuffle(teams);

这篇关于连续生成随机枚举值,而不会两次获得相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆