本文介绍了枚举中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把特殊字符,括号('('和')'和撇号(')放在枚举中。



我有这个:

 私有枚举specialChars {
(,),'
}

但它不起作用。 Java表示有关无效令牌的内容。
我如何解决这个问题?



Grtz
me.eatCookie();

解决方案

你可以这样做:

  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; //将返回,或代替COMMA或APOSTROPHE
}
}

使用示例:

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

//查找特殊字符
if(line.equals(SpecialChars.COMMA)
|| line.equals(SpecialChars.APOSTROPHE )
|| line.equals(SpecialChars.OPEN_PAREN)
|| line.equals(SpecialChars.CLOSE_PAREN)
){
//为特殊字符$ b $执行某些操作b}
}


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?

Grtzme.eatCookie();

解决方案

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

这篇关于枚举中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 00:54