//Program to demo 3 useful enum methods // .values() returns an array with all the enum values // .toString() returns a printable image of an enum value // .ordinal() returns the ordinal (position number) of an enum value // import java.util.Random; public class EnumDemo { public static void main(String[] args) { //In this program, we have to prefix Suit with PlayingCard. // because Suit enum type was declared in the PlayingCard class //An enum type automatically has a values() method // The values() method returns an array with all of the enum values // They are stored in the order in which the values are declared PlayingCard.Suit[] allSuits = PlayingCard.Suit.values(); //An enum type automatically has a toString() method // Display each value from the suits array for (int k = 0; k < allSuits.length; k++) System.out.println( k + ": " + allSuits[k] ); System.out.println(); //An enum suit automatically has an ordinal() method //ordinal() returns the ordinal (declaration position) of an enum value //We can do the same as above using a for-each loop and ordinal() for (PlayingCard.Suit suit : allSuits) System.out.println( suit.ordinal() + ": " + suit); System.out.println(); //Lets get 10 Suit values at random, and show the ordinal() of each Random gen = new Random(); for (int k = 1; k <= 10; k++) { //Randomly choose a Suit from the suits array int randomInt = gen.nextInt( allSuits.length ); PlayingCard.Suit aSuit = allSuits[ randomInt ]; //Show the random suit and its ordinal() System.out.println( aSuit + " has ordinal " + aSuit.ordinal() ); } } }