package enumEx; import java.util.Scanner; // examples of using enums public class MonthHarness { private static Scanner scan; // simple enum inside a class // technically available as MonthHarness.LightColor public enum LightColor { RED, GREEN, BLUE }; // example using LightColor enum public static void LightColorEnumEx() { System.out.println("What color, RED, GREEN, or BLUE?"); String str = scan.next(); // program crashes if they don't give one of the three valid values LightColor c = LightColor.valueOf(str.toUpperCase()); if (c == LightColor.RED) { System.out.println("redrum, redrum"); } switch (c) { case RED: System.out.println("Bold choice."); break; case GREEN: System.out.println("Not easy, is it?"); break; case BLUE: System.out.println("That's cool."); break; } } public static void printArray(Date[] list) { // elt is each Date in list, in turn for (Date elt : list) { System.out.println(elt); } } // example of switch statement using enum public static void monthOpinion(Month m) { System.out.println("The month of " + m); switch (m) { case FEBRUARY: System.out.println("Cold, but short"); break; case MAY: System.out.println("Everybody's birthday!"); break; case AUGUST: System.out.println("Too hot, too long"); break; case NOVEMBER: System.out.println("May contain turkey"); break; default: System.out.println("it's a month... meh"); break; } } // examples of using enum Month public static void main(String[] args) { scan = new Scanner(System.in); System.out.println("\n using LightColor enumeration"); LightColorEnumEx(); System.out.println("\n\n using Month enumeration"); Month m = Month.MARCH; System.out.println(m + " has " + m.days() + " days"); monthOpinion(Month.MAY); monthOpinion(m); // Month.values() returns array of all Months // so generate random index in that array // this gets us a random month monthOpinion(Month.values()[((int) (Math.random() * Month.values().length))]); Date d = new Date(m, 4); System.out.println("Chosen date " + d); // array of dates Date[] dlist = new Date[12]; // foreach loop -- curr is each Month from the array in turn for (Month curr : Month.values()) { // curr.ordinal() converts the Month to an int // so we can use as array index // choose random day of the month dlist[curr.ordinal()] = new Date(curr, (int) (Math.random() * curr.days()) + 1); } System.out.println("\n\nArray of random dates, one per month"); printArray(dlist); } }