Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Enumerators

Enumerators


Video Summary: https://youtu.be/ydCiWR3gwmo


An enumerator is a user-defined datatype, typically used to group related data into a set of "states." When you use an enumerator, the value will actually be stored as a number - the compiler does not keep track of the names you use. For example, you could create and use an enumerator for a stoplight as follows:


When you try to access the value of an enumerator, it will return which position that state was entered into the list. In the previous example, green is 0, yellow is 1, red is 2. You could change these values with the following:


Beyond readability and type security, another advantage of enumerators is that they can be used in switch statements, because they are stored as a number. In order to do this, you may need to use explicit typecasting, such as:


Exercise

Consider this solution to a previous exercise:


In this exercise, you will modify this example by adding an enumerator for the suit of the card and placing a symbol for hearts, diamonds, clubs, or spades (♥ ♦ ♣ ♠ or h d c s) in the top left and bottom right corner of the card. Note that if you choose to use the symbols themselves, the code will likely behave differently than you might expect because of the way they are encoded.

  1. Create an enumerator named suits that contains diamonds, hearts, clubs, spades
  2. Create a random number between 0 and 3 to determine which suit to use, and typecast it to be used with your enum
  3. Create a switch statement based on this enum and assign a symbol (♥ ♦ ♣ ♠ or h d c s) to a string. Note that if it is the symbol, it has to be a string, not a character, because symbols take up more space than characters allow
  4. Adjust the card format to have the symbol you assign in the top left and bottom right corner. If you are using the symbols themselves, you will need to ADD space to setw for the bottom right because of the encoding

Solution