Special Characters in an Enum

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();

1

3 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
   }
}
4

Enum constants must be valid Java identifiers. You can override toString if you would like them displayed differently.

public enum SpecialChars {

    OPEN_PAREN {
        public String toString() {
            return "(";
        }
    },

    CLOSE_PAREN {
        public String toString() {
            return ")";
        }
    },

    QUOTE {
        public String toString() {
            return "'";
        }
    }

}
8

You should use something like this instead:

private enum SpecialChars {
   LEFT_BRACKET('('),
   RIGHT_BRACKET(')'),
   QUOTE('\'');

   char c;

   SpecialChars(char c) {
     this.c = c;
   }

   public char getChar() {
     return c;
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest