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.
I'm using:
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:
The team is: TEAM2
The team is: TEAM2
The team is: TEAM4
The team is: TEAM2
The team is: TEAM3
The team is: TEAM2
But I need my program to output the an enum value once and once only. Thanks
Simply use Collections.shuffle.
List<Team> teams = new ArrayList<>();
Collections.addAll(teams, Team.values());
Collections.shuffle(teams);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With