Special characters in an enum

前端 未结 3 1356
情话喂你
情话喂你 2020-12-28 08:35

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

I had this:

private enum specialChars{         


        
3条回答
  •  甜味超标
    2020-12-28 08:51

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

提交回复
热议问题