Java

INDEPENDENT TOPIC 03 – ENUMs

 

 

LESSON NOTE

 

 

ENUMERATED TYPES

 

It is sometimes useful to create variables that can have a pre-defined set of values that the variable can have.  Enumerated types, also known as enums, allow us to do this in Java.

 

TWO-FILE SETUP

 

In Java, creating an enum requires us to create a separate file to define the enum.  We can then use that enum in other classes that are in the same folder as the enum file.

 

CLASSIC EXAMPLE

 

A classic example where an enum is useful is when we want to create a variable that can hold four possible values representing the different directions: north, east, south and west. 

 

One option would be to use an integer and simply associate each direction with a specific number.  So, 0 could be north, 1 could be east, 2 could be south and 3 could be west.  However, as our programs grow in complexity, remembering this setup is difficult and problematic.  The better approach is to use an enum.

 

We first start off by creating the enum type called Dir (which is short for Direction).  Notice that enum names should start with capital letters.  Because we often use the enum's name in the code, programmers tend to try to use shorter names.

 

The code to create the enum is:

 

//Filename: Dir.java

 

public enum Dir

{

    NORTH, EAST, SOUTH, WEST

}

 

Notice that the four possible values are all written in caps.

 

We can then use the Dir enum inside a program like normal variables.  However, their values can now only be set to either Dir.NORTH, Dir.EAST, Dir.SOUTH or Dir.WEST.

 

Below is an example of a class that uses the Dir enum from above.  It creates two enum variables, gives each of them a value and then outputs their value to screen.

 

//Filename: EnumTester.java

 

public class EnumTester

{

    public static void main(String[] args)

    {

         //declare an enum

         Dir d1;

         Dir d2;

        

         //set d1 and d2 to one of the possible values

         d1 = Dir.NORTH;

         d2 = Dir.WEST;

        

         //Output values

         System.out.println(d1);

         System.out.println(d2);

    }

}

 

The program above will output the following to screen:

 

 

NORTH

WEST

 

 

ENUMS IN CONDITIONS

 

We can test the value of an enum type by using the == symbol just like when we test integers or doubles.

 

Let's consider the following enum that stores different weapon types for an RPG game:

 

public enum Weapon

{

   SWORD, STICK, AXE, STAFF

}

 

The program below will create an enum and set its value to one of the options.  An if statement is then used to output a message related to the weapon type.

 

public class EnumTester2

{

    public static void main(String[] args)

    {

        Weapon w = Weapon.STICK;

       

        if (w == Weapon.SWORD)

        {

          System.out.println("Nice sword!");

        }

        else if (w == Weapon.AXE)

        {

          System.out.println("Axes are awesome!");

        }

        else if (w == Weapon.STICK)

        {

          System.out.println("A stick?  Seriously?");

        }

        else

        {

          System.out.println("Magical staffs rock!");

        }

    }

}

 

ORDINALS

 

Each possible value in an enum has an ordinal number associated to it. The first value has the number 0, the next has number 1, and then 2 and then 3 and so on…

 

One can also use the term index to refer to ordinal number.

 

Consider the Days enum below:

 

public enum Days

{

   MONDAY, TUESDAY,

   WEDNESDAY, THURSDAY,

   FRIDAY, SATURDAY,

   SUNDAY

}

 

The value MONDAY has the ordinal number 0.  The value TUESDAY has the ordinal value 1. And so on…

 

We can get the ordinal number by using

 

                       enumName.ordinal()

 

The example below shows this in action.

 

public class EnumTester3

{

   public static void main(String[] args)

   {

       Days today = Days.MONDAY;

       Days tomorrow = Days.TUESDAY;

       Days funDay = Days.SATURDAY;

      

       int ord1 = today.ordinal();

       System.out.println(today + " is number " + ord1 + ".");

 

       int ord2 = tomorrow.ordinal();

       System.out.println(tomorrow + " is number " + ord2 + ".");

 

       int ord3 = funDay.ordinal();

       System.out.println(funDay + " is number " + ord3 + ".");

   }

}

 

The program above will output the following to screen:

 

 

MONDAY is number 0.

TUESDAY is number 1.

SATURDAY is number 5.

 

 

VALUE AT ORDINAL NUMBER

 

So what if we want to do the opposite from the previous section.  Instead of providing the value to get the ordinal number, we want to provide the ordinal number and get the corresponding value.

 

We can do this by using the values() method that returns an array of all the possible values in the enum.  We then use the ordinal number as an index into that array.

 

Let's consider the following Month enum:

 

public enum Month

{

   JAN, FEB, MAR, APR,

   MAY, JUN, JUL, AUG,

   SEP, OCT, NOV, DEC

}

 

The program below sets an enum type to a value based on the ordinal numbers 0 and 5 (representing the 1st and 6th values in the enum).

 

public class EnumTester4

{

    public static void main(String[] args)

    {

        Month m1;

        Month m2;

       

         //Set m1 to the first value in the enum

        //So that value has ordinal number 0

       

        m1 = Month.values()[0];

       

        //Set m2 to the 6th value in the enum

        //So that value has ordinal number 5

       

        m2 = Month.values()[5];

       

        //Output results

       

        System.out.println(m1);

        System.out.println(m2);

    }

}

 

 

Let's look at the line

                       m1 = Month.values()[0];

for a moment.  First, Month.values() is called.  It returns an array containing all of the possible values for the Month enum in order.  We then specify that we want index 0 of that array which is JANUARY.  So, m1 gets JANUARY.

 

USER INPUT

 

It is sometimes required that we get the user to input their choice and store that choice in an enum.  This can be done very effectively using the above method.

 

Let's consider the following MenuItem enum:

 

public enum MenuItem

{

   PIZZA,

   WINGS,

   FISH_AND_CHIPS,

   STEAK,

   PASTA,

   NACHOS

}

 

The following program now gets the user to input his/her choice to order and we store that in the enum by using the array provided by values() which is the same concept as in the previous example.

 

public class EnumTester5

{

    public static void main(String[] args)

    {

         MenuItem order1;

        

         Scanner s = new Scanner(System.in);

         System.out.println("What would you like?");

         System.out.println("0-Pizza         3-Steak");

         System.out.println("1-Wings         4-Pasta");

         System.out.println("2-Fish & Chips  5-Nachos");

         int choice = s.nextInt();

        

         order1 = MenuItem.values()[choice];

        

         System.out.println("You ordered " + order1 + ".");

    }

}