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
Use Collections shuffle method:
This code returns all values in a random order, and resets the list when exhausted to repeat the process indefinitely.
Simply use Collections.shuffle.
What about this? It is recursive!
It is better to shuffle collection and return elements one by one.