我有一个我想要随机的enum团队。所以我有:
public enum Teams { TEAM1, TEAM2, TEAM3, TEAM4, TEAM5, TEAM6; }
然后我有一个随机方法来随机生成值:
public static Teams getRandomTeam() {
return Teams.values()[(int) (Math.random() * Teams.values().length)];
}
这会返回一个随机生成的团队,但是我需要,一旦团队生成,说TEAM2,它就不能再生成了。
我正在使用:
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());
(我知道这是错误的,因为它一遍又一遍地调用这个方法。
在我运行程序的那一刻,输出可能是:
团队是:TEAM2
团队是:TEAM2
团队是:TEAM4
团队是:TEAM2
团队是:TEAM3
团队是:TEAM2
但是我需要我的程序只输出一次enum值。 感谢
答案 0 :(得分:10)
只需使用Collections.shuffle。
List<Team> teams = new ArrayList<>();
Collections.addAll(teams, Team.values());
Collections.shuffle(teams);
答案 1 :(得分:5)
最好逐个收集和返回元素。
private static List<Teams> tList;
private static void regenerateList() {
tList = new ArrayList<Teams>(Arrays.asList(Teams.values()));
Collections.shuffle(tList);
}
public static Teams getRandomTeam() {
if (tList.size() > 0) {
return tList.remove(0);
} else {
//handle as you wish: return null or regenerate the list
regenerateList();
return getrandomTeam();
}
}
答案 2 :(得分:1)
这个怎么样?这是递归的!
public static enum TEAMS {
TEAM1, TEAM2, TEAM3, TEAM4, TEAM5, TEAM6;
}
TEAMS[] teams = TEAMS.values();
Random rnd = new Random();
public TEAMS getnextRandomTeam() {
int indx = rnd.nextInt(teams.length);
TEAMS t = teams[indx];
teams[indx] = null;
return t == null ? getnextRandomTeam() : t;
}
答案 3 :(得分:0)
使用Collections shuffle方法:
List<Teams> teams = new ArrayList<Teams>(Arrays.asList(Teams.values()));
int index = Integer.MAX_VALUE;
public Teams getRandomTeam() {
if (index >= teams.size()) {
Collections.shuffle(teams);
index = 0;
}
return teams.get(index++);
}
此代码以随机顺序返回所有值,并在耗尽时重置列表以无限期地重复该过程。