// EnumDemo.java - demonstrates some enum features // cmc, 10/10/05 import java.util.Scanner; public class EnumDemo { // define an enumeration to represent types of fruit enum Fruit { APPLE, PEAR, ORANGE, GRAPE, PEACH } // no semi-colon required public static void main(String[] args) { // print all fruit types by enhanced for loop over the values System.out.println("Fruit choices:"); for (Fruit f : Fruit.values() ) System.out.println(f); // get a fruit type from the user as a string System.out.println("What type of fruit do you want?"); Scanner in = new Scanner(System.in); String fruitString = in.next(); // get associated Fruit - may throw IllegalArgumentException Fruit userFruit = Fruit.valueOf(fruitString); // use values as constant case labels of switch structure switch (userFruit) { // compiler knows the cases are Fruit values case APPLE: case PEACH: System.out.println("Umm. Good for pie."); break; case PEAR: System.out.println("Hmmm. Odd shape."); break; case ORANGE: case GRAPE: System.out.println("Ahh. Refreshing juice."); } // but must spell out completely in some situations // if (userFruit == PEAR)... causes "cannot find symbol" error if (userFruit == Fruit.PEAR) // compiler insists on Fruit. System.out.println(" :-)"); } }