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();
@HunterMcMillen: Yes, but using if(line == SpecialChars.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With