Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special characters in an enum

Tags:

I want to put the special characters, the parentheses ( '(' and ')' ) and the apostrophe ('), in an enum.

I had this:

private enum specialChars{
   "(", ")", "'"
}

but it doesn't work. Java says something about invalid tokens. How can I solve this?

Grtz me.eatCookie();

like image 209
Confituur Avatar asked May 01 '12 14:05

Confituur


People also ask

Can enum have special characters?

@HunterMcMillen: Yes, but using if(line == SpecialChars.

Can enum have special characters C#?

Sometimes you might need to loop on the elements of a particular enum and print its element names, however as you know by the language constraints, the enum element names must follow the naming convention, you cannot include spaces or other special characters.

Should enum be uppercase or lowercase?

Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.


1 Answers

You could do something like this:

private enum SpecialChars{
   COMMA(","),
   APOSTROPHE("'"),
   OPEN_PAREN("("),
   CLOSE_PAREN(")");

   private String value;
   private SpecialChars(String value)
   {
      this.value = value;
   }

   public String toString()
   {
      return this.value; //will return , or ' instead of COMMA or APOSTROPHE
   }
}

Example use:

public static void main(String[] args)
{
   String line = //..read a line from STDIN

   //check for special characters 
   if(line.equals(SpecialChars.COMMA)      
      || line.equals(SpecialChars.APOSTROPHE)
      || line.equals(SpecialChars.OPEN_PAREN) 
      || line.equals(SpecialChars.CLOSE_PAREN)
   ) {
        //do something for the special chars
   }
}
like image 86
Hunter McMillen Avatar answered Oct 23 '22 16:10

Hunter McMillen