Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...